objective c - When not to alloc and init an NSString -


Whenever I need to create a new NSString variable, I always allocate and I init it. It seems that there are times when you do not want to do this. How do you know when when nosting is allocated and when not?

whenever i

not understand this Does not come in.

Variable The program is present from the moment, where you declare it:

  NSString * myString;  

This variable is not an NSString, it is storage for an indicator for NSString. This is what * indicates: this variable holds an indicator.

The NSString object exists only when you create one:

  [[NSString alloc] init];  

and the pointer of that object is only in the variable from the time you give it to:

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

Thus, if you are going to get a string object somewhere (e.g., substringWithRange: ), you create a new, empty one Because you can change the pointer to the other with the pointer in the empty string.

Sometimes you want to create an empty string; For example, if you want to get a bunch of stars at one time (like, from an NSScanner) and want to add some or all to a large string, you can use an empty temporary string ( Eloc and init ) and send it to appendstring: message to codify it.

You have to do issued any item that you create by alloc is one of these rules.


Comments