NSString *s1 = @"string1";
// NSString *s2 = [[NSString alloc]stringWithFormat:@"string2"];
NSString *s2 = [[NSString alloc] initWithFormat:@"string2"];
I know this is pretty basic concept but I am not 100% clear with this.
First one doesn’t allocate a memory address and send one allocates a memory address…
Also second one increases the reference count of the variable but not the first one…
Even though I understand the concept but don’t know the situation when I should use the first one or the second one..
When should I use the first one ? also when should use for the second one?
Thanks in advance..
You should never use the second one –
+stringWithFormat:is a class method. Including your first example, you have basically 3 choices:s1in this case is a pointer to a constant string.s2ands3both point to new strings that you’ve created, buts2has been retained for you, ands3has been autoreleased. If you just need a temporary object, the autoreleased objects3or the constant objects1are good choices. If you need to keep the string around, you should uses2(actually now that I think about its1will work in this case too – it’s not really idiomatic, though).You can make
s1ors3equivalent tos2by sending them aretainmessage. You could also turns2into an equivalent object by sending it anautoreleasemessage.