iPhone Dev - NSString Creation - iphone

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. ****

Related

Difference between these two NSString methods

So I just got asked this at an interview today and after some googling am still unable to figure out the answer (in fact I couldn't even find any code at all which used the [NSString string] method).
What is the difference between
NSString *someString = [NSString string];
NSString *someString = [[NSString alloc] init];
Now my initial thoughts were that [NSString string] would return an object which would be autoreleased whereas using alloc and init would return an object which has been retained. However it seems that this answer was incorrect.
I've looked at the NSString class reference in the apple docs but all it says is
Returns an empty string.
+ (id)string
Return Value
An empty string.
Could somebody explain to me exactly what the difference between these two are?
Was that your response, and did you ask why your answer was incorrect? I ask because your assumption is mostly correct (at a higher level).
It's not exactly 'retained' when returned from alloc+init, it is an object you hold one reference to, and should balance with a release or autorelease. For the convenience constructor (+[NSString string]), you are returned an object which you hold zero references to, but one which you can expect to live until the current autorelease pool is popped unless you send it an explicit retain (assuming MRC or ARC, since it is tagged iOS).
At the lower level, you could make some guesses, but I wouldn't expect that question in many objc interviews (unless you told them you were mid or senior level). Basically, it is implementation defined, but both forms could return the same static, constant NSString (that may have been what the interviewer was looking for). To illustrate:
#implementation NSString
static NSString * const EmptyNSString = #"";
- (id)init
{
self = [super init];
[self release];
return EmptyNSString;
}
+ (id)string
{
return EmptyNSString;
}
...
Again, that's implementation defined, but an obvious optimization. As well, that optimization makes physically subclassing concrete immutable types (NSString) difficult for mutable variants (NSMutableString) in some cases.
Now my initial thoughts were that [NSString string] would return an object which would be autoreleased
Technically, it’s a placeholder string that is constant, i.e., it lives throughout the entire program execution, never being released. It’s not an autoreleased string. Conceptually, and this is what I’d focus as an interviewer, it’s a string (an empty string) that is not owned by the caller, hence the caller shouldn’t release it.
whereas using alloc and init would return an object which has been retained
Technically, it’s a placeholder string that is constant, i.e., it lives throughout the entire program execution. In fact, it’s the same object as the one above, and it is not retained. Conceptually, and this is what I’d focus as an interviewer, it’s a string (an empty string) that is owned by the caller, hence the caller is responsible for releasing it when it’s not needed any longer.
The correct answer is that
NSString *someString = [NSString string];
gives you an empty string that you do not own and that you must not release (according to the memory management rules)
whereas
NSString *someString = [[NSString alloc] init];
gives you an empty string you do own and that you must release (according to the memory management rules).
Without poking into the implementation, you can't say anything else about those two strings. You can't say that they are autoreleased, because they might not be and you can't say what the retain count will be.
In actual fact, you'll probably get (in both cases) the same pointer to a constant object of some NSString subclass, probably with a retain count of UINT_MAX which is used by the run time as a flag to disable normal retain release behaviour for constant strings. I haven't actually tried the above because nobody except the maintainers of the Objective-C SDK needs to care.
You don't often see
NSString *someString = [NSString string];
because it's the same as
NSString *someString = #"";
which is shorter. It's usually used to create an empty NSMutableString
NSMutableString* s = [NSMutableString string];
The only thing I can imagine is that:
Won't allocate memory since it is not made with alloc. It is a constant (an empty string) made by the system and doesn't need to be released.
You allocate the memory for the NSString yourself which means you have to keep track if the NSString still 'lives' or not when you are done with it, and thus need to release it.

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.

NSString property making a shallow copy

I am having some trouble understanding what is going on with these two string properties declared in separate classes:
#property (nonatomic, copy) NSString *userPhone;
and
#property (nonatomic, copy) NSString *userLogin;
Somewhere in the code I go and do the following:
user.userPhone = self.userLogin;
What I would expect is that userLogin gets copied into a new object and assigned to userPhone. However, I found out that they both share a reference to the same object! So when userLogin get released, so does userPhone, breaking my poor app.
I know that I am missing something about memory management here, but I don't understand why copy does not work in this case.
Anyone knows?
Thanks a lot
NSString objects are immutable, meaning that their contents can not change once they have been created. To exploit this, the copy method does not create a new string. Instead, it retains the original string*. This is an internal optimization, from your point of view standard memory management rules apply. If you have problems with the string being deallocated before you expect, you must be over-releasing it somewhere else.
stringWithString: is also internally optimized in the same manner. If you pass an immutable string as the argument, it will not create a new one*. If you execute the following code, you will see that string1 and string2 addresses are the same.
NSString *string1 = #"Test";
NSString *string2 = [NSString stringWithString:string1];
NSLog(#"%p, %p",string1, string2);
(*) These are implementation details that are subject to change at any time.
You may be double releasing the original. If i remember the copy property will actually just retain an immutable copy (i.e NSString) and only do a hard copy if it is mutable (NSMutableString). Its possible the original string is autoreleased and you give it a hard release, accounting for two decrements.
Edit:
After reading other posts i have changed mine to reflect.

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 ..].

problem with assigning NSNumber

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.