Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of NSMutableString vs NSString?

I am confused between NSString and NSMutable string usage. Suppose I have instance variables one and two declared in class like this:

NSString *one;
NSMutableString *two;

let us suppose I have created setters and getters of them using properties.

lets say I have changed my "two" string like these:

     1. [two appendString:@"more string"];
     2. two = @"string"
     3. self.two = @"string"

Questions:

  1. would 1st line release previous string and allocate new object and assign value to it. if yes, then does that mean creating getters and setters are unnecessary in this case ? OR its unnecessary to create properties in NSMutablestring

  2. In this case would the previous allocated string object released ?

  3. Its for sure that first object would be released as we are calling setters here. is this code necessary or we can just use the code line 2 to assign string.

Now about NSString: As can modify the string like this also :

    one = [one stringByAppendingString:@" more string"];
    self.one = [one stringByAppendingString:@" more string"];

Which is better using NSMutablestring or NSString ?

Sorry for long post, but I needed to understand these concepts.

like image 777
user1374408 Avatar asked Dec 26 '22 23:12

user1374408


1 Answers

For the first part of your question:

  1. Almost definitely not. I expect the memory will be allocated dynamically, rather than released and reallocated.

  2. If the previous answer is no, this is also, no.

  3. The second and third options don't even work with the warning Incompatible pointer types assigning NSMutableString to NSString

I expect NSMutableString will be slightly more efficient in terms of memory as you are indicating early on that the program may need memory dynamically. NSString is likely to be allocated a single, suitably sized block of memory.

Your views of NSMutableString seem to be what the stringBy.. methods of NSString will do:

With NSString and its stringBy... methods, you are creating new objects, releasing the old one (if need be) and making the new object autorelease. (Take care if you are changing from non-autorelease to autorelease, you may have a release in your dealloc that isn't needed anymore)

like image 93
James Webster Avatar answered Dec 29 '22 13:12

James Webster