自动释放对象和自动释放池(1)

来源:转载

Autoreleasing Objects

• Calling -autorelease flags an object to be sent release at some

point in the future

• Let’s you fulfill your retain/release obligations while allowing anobject some additional time to live
• Makes it much more convenient to manage memory
• Very useful in methods which return a newly created object

 

Method Names & Autorelease
• Methods whose names includes alloc, copy, or new
return a retained object that the caller needs to release

NSMutableString *string = [[NSMutableString alloc] init];
// We are responsible for calling -release or -autorelease
[string autorelease];


• All other methods return autoreleased objects

NSMutableString *string = [NSMutableString string];
// The method name doesn’t


• This is a convention- follow it in methods you define!

 

Hanging Onto an Autoreleased Object
• Many methods return autoreleased objects
  ■ Remember the naming conventions...
  ■ They’re hanging out in the pool and will get released later
• If you need to hold onto those objects you need to retain them
  ■ Bumps up the retain count before the release happens
name = [NSMutableString string];
// We want to name to remain valid!
[name retain];
// ...
// Eventually, we’ll release it (maybe in our -dealloc?)
[name release];

 

Side Note: Garbage Collection
• Autorelease is not garbage collection
• Objective-C on iOS does not have garbage collection


分享给朋友:
您可能感兴趣的文章:
随机阅读: