Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When not to alloc and init an NSString

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?

like image 596
node ninja Avatar asked Sep 27 '10 04:09

node ninja


People also ask

What is a NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

What is Alloc init in Objective C?

This is an instance variable of the new instance that is initialized to a data structure describing the class; memory for all other instance variables is set to 0 . You must use an init... method to complete the initialization process. For example: TheClass *newObject = [[TheClass alloc] init];


1 Answers

Whenever I need to create a new NSString variable I always alloc and init it.

No, that doesn't make sense.

The variable exists from the moment the program encounters the point where you declare it:

NSString *myString;

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:

[[NSString alloc] init];

and the pointer to that object is only in the variable from the moment you assign it there:

myString = [[NSString alloc] init];
//Or, initializing the variable in its declaration:
NSString *myString = [[NSString alloc] init];

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 alloc and init) and send it appendString: messages to do the concatenations.

You also need to release any object you create by alloc. This is one of the rules in the Memory Management Programming Guide.

like image 103
Peter Hosey Avatar answered Oct 02 '22 13:10

Peter Hosey