Whenever I need to create a new NSString variable I always alloc and init it. It seems that there are times when you don’t want to do this. How do you know when to alloc and init an NSString and when not to?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, that doesn’t make sense.
The variable exists from the moment the program encounters the point where you declare it:
This variable is not an NSString. It is storage for a pointer to an NSString. That’s what the
*indicates: That this variable holds a pointer.The NSString object exists only from the moment you create one:
and the pointer to that object is only in the variable from the moment you assign it there:
Thus, if you’re going to get a string object from somewhere else (e.g.,
substringWithRange:), you can skip creating a new, empty one, because you’re just going to replace the pointer to the empty string with the pointer to the other one.Sometimes you do want to create an empty string; for example, if you’re going to obtain a bunch of strings one at a time (e.g., from an NSScanner) and want to concatenate some or all of them into one big string, you can create an empty mutable string (using
allocandinit) and send itappendString:messages to do the concatenations.You also need to
releaseany object you create byalloc. This is one of the rules in the Memory Management Programming Guide.