problem with assigning NSNumber - iphone

I have an instance of NSNumber * did inside a class called Reservation.
Below myres is an instance of Reservation
myres.did = [[NSNumber alloc] initWithInt:[[[data objectForKey:#"discount"] did] intValue]];
When I do this everything works just fine. However the code is ugly, and when I do:
myres.did = [data objectForKey:#"discount"] did];
My code breaks down.. I know that [[data objectForKey:#"discount"] did] returns an object, which is an NSNumber.
Can some explain to me why is this? and what do I need to change in my code if I want to assign a NSNumber with another NSNumber?

Where does the code break down? Do you have a crash happening in your application?
By the way, in the second example, you have a mismatched set of square brackets.
On a conceptual level, the first code example puts a retained object into myres.did, but the second example puts an autorelease object into myres.did. If you later do a release on myres.did by using the second code snipped, you will probably get a crash.

First ensure that your object's property is set to retain:
#property (nonatomic, retain) NSNumber *did;
and that you are releasing that object in your dealloc.
Unfortunately the copy you have in place cannot become any shorter. What you are in effect doing with this statement:
myres.did = [[NSNumber alloc] initWithInt:[[[data objectForKey:#"discount"] did] intValue]];
is taking the integer value from one NSNumber reference and moving it into another. The integer contents, being non-referential (assign), can move this way. The NSNumber itself cannot be copied as it is immutable. Please see this post for more info. You must have another issue within your code, perhaps an inappropriate release.

Please see this supplemental answer which gives background to the copying of NSNumber.

Related

Why create a variable rather than direct assignment?

This is a basic question, and I'm not really sure what to search for to see if its been asked before.
In a lot of examples, I've seen property assignments handled like this:
NSArray *tempArray = [/*some code to get array*/];
self.propertyArray = tempArray;
[tempArray release];
Why not just do:
self.propertyArray = [/*some code to get array*/];
What's the difference between the two?
This answer is assuming your not using ARC.
The first code snippet, is the way Apple recommends initializing a property as long as you are doing this in any method besides init. You'll notice Apple code snippets do this a lot. It makes it much easier to manage your memory, and in my opinion it makes it easier to read.
NSArray *tempArray = [[NSArray alloc] initWith....]
self.propertyArray = tempArray;
[tempArray release];
The second code snippet you have could potential lead to a memory leak depending how you set up the NSArray.
This would be a leak. The propertyArray would have an retain count of 2. After you release the instance variable in dealloc, you still have a retain count of 1. That is a leak.
self.propertyArray = [[NSArray alloc] initWith...];
This would be okay, because they both are being autoreleased, which would give you a retain count of 1. As, long as you release the instance variable in dealloc.
// Class Method so autoreleased
self.propertyArray = [NSArray arrayWith....];
// Explicitly declaring autorelease
self.propertyArray = [[[NSArray alloc] initWith.....] autorelease];
It's simply just a matter of preference. I prefer the first way, I think it is easier to to read and follow.
Edit (with ARC):
All these methods would be acceptable with the exception of the release statement and autorelease statement.
[tempArray release];
ARC automatically takes care of the memory management for you, so you do not have to explicitly release them. This is the benefit of ARC, you can create as many objects as you want without the headache of trying to figure out where to release them.
Also, your property would be different. You must either use strong or weak, and not retain. In this case strong would be the solution.
#property (nonatomic, strong) NSArray *tempArray;
In the second example, you don't release the object, which is retained by the property, so you have a memory leak.
self.propertyArray = [[SomeClass alloc] init];
// ^ no release
With ARC, the two statements are equivalent in practice (although you would have to omit the release call for it to actually compile in ARC).
In a manual managed memory scenario, you would leak tempArray in the second ("direct assignment", which it isn't because you're calling a property setter not setting an ivar) example, as you do not have a release call on tempArray to balance it's alloc/init.
The the useful distinction is reduced to expressiveness, the ability to debug, and ultimately the programmers personal preference.
Your first example is the way it was done before the advent of automatic reference counting (ARC). The second example works fine under ARC. Unless you have to do it the old-fashioned way, select ARC for all your projects.
Code like that most likely means that somebody wanted an ability to debug it easier. Basically if you have a separate variable, you can print it out in the debugger without triggering (possibly custom) property setters and getters.

objective-c: when to autorelease an nsnumber object when not using alloc

I noticed that my program was crashing because it was running out of memory. I figured out that this was happening because of this code segment:
DataSet *tempSet = [[DataSet alloc] init];
tempSet.rightFoot = [NSNumber numberWithDouble:temp1];
tempSet.leftFoot = [NSNumber numberWithDouble:temp2];
[footData addObject:tempSet]; //add dataSet object to the array
[tempSet release];
I read some tutorials about memory management online and was able to figure out that I needed to do this: (notice the added "autoreleases")
DataSet *tempSet = [[DataSet alloc] init];
tempSet.rightFoot = [[NSNumber numberWithDouble:temp1] autorelease];
tempSet.leftFoot = [[NSNumber numberWithDouble:temp2] autorelease];
[footData addObject:tempSet]; //add dataSet object to the array
[tempSet release];
I am still confused about why I had to do this. I did not use alloc, new or copy when creating the numberWithDouble.
Does this mean that I would need to add autorelease in this situation as well?:
[subset addObject:[NSNumber numberWithDouble:temp]];
What about this situation?:
tempSet.rightFoot = [NSString stringWithString:#"temp"];
I appreciate any help.
+numberWithDouble
is called a convenience method. Meaning, it replaces the little section of code that would look like this:
[[[NSNumber alloc]initWithDouble:double]autorelease];
Most (if not all) convenience methods are auto release by default, so the OP code with the autoreleases is incorrect, as it drops the retain count to -1.
The equals sign however is equivalent to
[self setRightFoot:[[[NSString alloc]initWithString]autorelease]];
which increments rightFoot's retain count and requires it to be released elsewhere.
as for the -addObject code, it returns void, so it does not in fact increment the receiver's retain count, and requires no release of the receiver. The object in the array should already be released by the convenience method for later, which doesn't matter because the array is now holding "copy" of it.
This is not an answer (I just do not know how to comment -- I only see "share, edit, flag"), but just a few info about Memory Management in iOS:
1. Don't release objects that you do not own.. ---> owned objects are usually the ones you "alloc", "new", "copy." //And probably the one in your #property wherein you "retain" an object.
2. when you "autorelease" an object, don't "release" it afterwards, because that would mean you're releasing the same object twice.
But there's ARC already, so you better upgrade your Xcode to avoid overreleasing objects / memory leaks (for not releasing objects)..
If there's something wrong or inappropriate with the one I put here, please edit. :)

ObjctiveC yet another retain-copy-release error [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Objective C alloc/release error
When I try the code below it crashes with BAD_ACCESS if I release newString. What am I missing here?
As far as I know, when I use "copy" as an accessor I got the ownership of the object, so even should I release the other referencing pointer, retain count should still stay 1+, so that object should still be in memory?
P.S. This is a singleton class if it makes a difference.
.h file
NSString *originalString;
#property (nonatomic,copy) NSString *originalString;
.m file
#synthesize originalString;
...
NSString *newString = [[NSString alloc] init...];
self.originalString = newString;
[newString release]; //this lines makes it crash
I've also tried
self.originalString = [newString copy];
with no luck..
Have you tried using retain instead of copy?
http://wiki.cs.unh.edu/wiki/index.php/Objective_C_Property_Attributes#Setter_Semantics
I'm not really sure whether or not this would actually work if copying doesn't, but using retain instead of copy should cause the reference count to the string to increment by 1 when assigned to the property, bringing it up to 2 from the 1 it was when the string was alloced, so when you use [newString release]; on the line after the property assignment, the string should end up with reference count 1 and thus continue to exist.
[newString relase]; //this lines makes it crash
relase probably isn't the name of a method. Did you mean release?
Assuming the above was just a typographical error in your question, and not an error in your code, then your code is correct, and you'll need to provide more information about the error. Pasting the actual code of the method in question would be helpful in that case.
this code looks correct, are you sure the crash isn't somewhere else?
EDIT: as noted in the comments, NSString being immutable won't cause the copy to allocate a new object. I've edited the answer for the mutable case, just in case someone stumbles into this later and doesn't read the whole thing.
Now back with our regular programming.
Don't know if this might be the problem, but note that, if you were using a mutable object like NSMutableString, with copy you would not increment the retain count, you would effectively create a new object, so what would happen:
NSMutableString* newString = [[NSMutableString alloc] init..]; // allocate a new mutable string
self.originalString=newString; // this will create yet another string object
// so at this point you have 2 string objects.
[newString relase]; //this will in fact dealloc the first object
// so now you have a new object stored in originalString, but the object pointed
// to by newString is no longer in memory.
// if you try to use newString here instead of self.originalString,
// it can indeed crash.
// after you release something, it's a good idea to set it to nil to
// avoid that kind of thing
newString = nil;
Have you tried just adding autorelease to your *newString init? Then just take out the manual release all together.
NSString *newString = [[NSString alloc] init...] autorelease];
You may consider to migrate your codes to Xcode 4.1 with ARC, then you would not need to worry about retain and release of objects.

Syntax for accessing instance variables? (Objective-C)

What is the proper syntax for accessing an instance variable in Objective-C?
Assume we have this variable:
#interface thisInterface : UIViewController {
NSMutableString *aString;
}
#property (nonatomic, retain) NSMutableString *aString;
and that it is synthesized.
When we want to access it, we first would want to allocate and initialize it. Having programmed in Objective-C for about a month now, I've seen two different forms of syntax. I've seen people do simply aString = [[NSMutableString alloc] initWithString:#"hi"], where they allocate the string like that; I've also seen people start it off with self.aString and then they proceed to initialize their ivar. I guess I'm just trying to figure out what is the most proper way of initializing an instance variable, because with the former example, I have received EXC_BAD_ACCESS errors from it. After prepending the self. though, it didn't appear.
Forgive me if this is a duplicate question, but after reading some posts on SO, it's made me curious. I'm trying to learn the proper syntax with Objective-C because I prefer being proper rather than sloppy.
If you have declared a property and #synthesize it in the .m file, you simply set it like this:
self.aString = #"hi"; // or [[NSMutableString alloc] initWithString:#"hi"];
Using self.varName takes advantage of what your property declaration actually does- it handles retention of the new value (since your property has the retain attribute), releasing the old value, etc for you.
If you just do:
aString = someValue;
... you may be leaking the original value that was in aString, since without using self.aString you are accessing the variable directly vs through the property.
Note the difference between self->varName and self.varName
The first is pointer access. The second is property access.
Why is that important? Pointer access is direct. Property access, on the other hand makes use of getters and setters (be they #synthesized or not). Moreover, as a convenience, the #synthesized accessors take care of the memory mangement for you (i.e. when using self.varName = ...;), whereas varName = ...; does only what it says, i.e. the assignment -> (there lies the explanation for EXC_BAD_ACCESS errors you might be getting).
Syntactically, both forms are correct. If you want to better communicate intent, use self->varName when you want to work directly with the pointer and use self.varName when you want to take advantage of the #property convenience.
Here are all the possible combinations (I think)
OKs and BADs are only correct when aString property has retain attribute:
#property (nonatomic, retain) NSMutableString *aString;
So:
1
aString = [[NSMutableString alloc] init]; //OK:
This is OK but only in the case aString is not pointing to an invalid object or you will loose a reference to that object and it will leak because you won't be able to reach it to release it.
2
aString = [NSMutableString string]; //BAD
Bad because you are suppose to retain aString (as you declared it that way), you are not retaining it and you will get surely get EXC_BAD_ACCESS in the future
3
aString = [[NSMutableString string] retain]; //OK
Same as the first approach, only good if aString is not pointing to a valid object. However I will use the first though.
4
aString = [[[NSMutableString alloc] init] autorelease];//BAD
Same as the second approach.
5
self.aString = [[NSMutableString alloc] init]; //BAD!!
Bad because you are retaining it twice, hence it will lead to memory leaks
6
self.aString = [[NSMutableString string]; //******GOOD!******
This is probably the safest. It will be retained by the property setter and since you are using the setter any other object that could have been pointed by aString will be released appropriately
7
self.aString = [[NSMutableString string] retain]; //BAD
This is retained twice.
8
self.aString = [[[NSMutableString alloc] init] autorelease];//Ok
This is also OK, but I would use the convenience method instead of this long approach :)
Be wary that the #1 and #3 options are perfectly good if you know what you are doing. In fact I use them much more frequently than #6
I personally prefer to use the self. syntax. It just makes it easier to determine that its an instance variable, and not just some other variable in the current scope that will be lost when its NSAutoreleasePool is drained. However, it is correct to use them both ways, and if you are receiving EXC_BAD_ACCESS errors, it is not because you accessed it without using self.. You are correct in saying that you must alloc it, and whichever way you choose to access your variables, keep it consistent or you will receive errors.
I hope this helps.
Always use accessors except in init, dealloc and in accessors themselves. Doing this will save you a lot of headaches like the one you're describing. Also, name your ivars something different than your property (_foo, foo_, mFoo, but not foo).
self.foo is precisely the same as [self foo]. I calls the method foo. self.foo = x is precisely the same a [self setFoo:x]. It calls the method setFoo:. If you synthesized the property foo as a retain variable, then this looks something like:
#synthesize foo = foo_;
- (void)setFoo:(id)value {
[value retain];
[foo_ release];
foo_ = value;
}
This correctly releases the old value of foo_, assigns a new one and retains it.
foo = x (assuming foo is an ivar) does not call any method. None. It just assigns the value of the pointer in x to the pointer in foo. If foo pointed to something that was retained, it's leaked. If the new value you're assigning isn't retained, you'll crash later.
The solution to this is to always use accessors when you can.
Either.
Using the dot syntax is cleaner (to some) and it compiles to the equivalent. i.e self.iVar is the same as [self iVar] and self.iVar = aValue is the same as [self setIVar:aValue];
self.aString is a syntactic sugar to [self aString]. Synthesize a property just create the -aString and -setAString: method (depending on the property you have chosen it while not be the trivial affectation).
Now the question is whether to use the . notation. I suggest you not to use it.
Why? First know that Objective-C aim to be just an addition to C. This mean that every valid C code is also a valid Objective-C code.
Now look at what they have done with the dot notation. The last statement does not hold anymore. You wont distinguish between an access to a field of a C structure and sending objective-c method.
So please don't use the dot notation. Prefer using the [self ..].

iPhone Dev - NSString Creation

I'm really confused with NSStrings. Like when should I do
NSString *aString = #"Hello";
of should it be:
NSString *aString = [[NSString alloc] initWithString:#"Hello"];
But then its different when you're assigning a value to an NSString property isn't it?
Can someone clear this up for me?
Thanks!!
In general you should do the first, but they are mostly functionally the same. You can treat constant NSStrings just like normal NSString string objects, for instance:
[#"Hello" length]
will return 5. You can assign them to properties, everything just works. The one thing you might notice is that with the constant NSStrings you don't have to worry about retain/release. That is because they are actually mapped into the applications readonly data section, and don't have allocated memory. Retain and release calls against them still work, they just become noops.
NSString *aString = #"Hello";
Will create an autoreleased string. That is, if you don't explicitly retain it, it will might disappear after your method is over (and sometimes that's totally fine). But if you want to hold on to it past that time, you'll need to retain it.
If you create a property for that string like this
#property (retain) NSString *aString;
And then assign like this:
self.aString = #"Hello";
Then you've properly retained the string and it will stick around.
On the other hand, using alloc, init will create a string for you with a retain count of 1, and if you don't need it past that method, you should release it.
****Edit: #"Hello" is not an autoreleased string, as others have pointed out. My bad. ****