简体   繁体   中英

NSString basics - memory - retain - copy

Here is my code:

NSString *xyz=[NSString stringWithFormat:@"%i %@",10,@"Sagar"];

Now I am taking other string, as follows.

NSString *x2=[xyz copy];

I don't know exactly what will happen here? Is it something like, x2 has the ref of xyz's ref?

NSString *x3=[xyz retain];

What will happen here, x3 has a new memory having copied string or [xyz copy] does that?

Now, how to remove all these three strings from memory?

NSString *xyz=[NSString stringWithFormat:@"%i %@",10,@"Sagar"];

This will create autoreleased instance of NSString - it will be released when the autorelease pool is drained (typically on the next run loop).

NSString *x2 = [xyz copy];

In theory -copy message will create a new instance of the object with retain count 1 (that is you must release it somewhere), but as NSString object is immutable then [xyz copy] will be optimized to [xyz retain] and thus it will point to the same instance.

NSString *x3=[xyz retain];

x3 will point to the same instance as xyz (and x2), and its retain count will be incremented - you must release your object somewhere.

Now, how to remove all these three strings from memory?

Make sure that you pair all retain (copy) messages with release and memory will be freed.
Read Objective-c memory management guide for more details.

In situation like this it is especially helpful to familiarize yourself with the message naming conventions/rules associated with memory management in objective-c and cocoa (and related frameworks):

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it. ( Memory Management Programming Guide for Cocoa )

consequently, you can assume, that every object that you ever receive from a message that is not named according to the scheme laid out above is either autoreleased or taken care of by some other means (it may be a shared object managed by some other object etc.)

If you just keep this in mind, your questions can be answered quickly:

  1. You receive the NSString *xyz from a message whose name does not match the scheme described in the rule above (not alloc, not new, not copy, not retain). You must not release it.

  2. You receive the NSString *x2 from a message named copy. You must release it

  3. You receive the NSString *x3 from a message named retain. You must release it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM