简体   繁体   中英

Memory Management in iOS

Hello everyone (sorry for my english). I'm new with objetive-C and iOS programming. May you help me?

@interface RootViewController : UITableViewController 
{
    NSMutableArray *keysFromQuery;
}

@property (nonatomic, retain) NSMutableArray *keysFromQuery;
....
....
NSString *category = [keysFromQuery objectAtIndex:0];

What will happen with [keysFromQuery objectAtIndex:0] if I do: [category release];?

What will happen with category if I do after that: [keysFromQuery release];?

I don't know well how references and memory mechanisms work.

Thanks!

Don't call -release on category . You don't own the object. You must only release objects which you have taken ownership of, via NARC (new/alloc/retain/copy). For more info read the Memory Management Programming Guide .

不要释放对象,因为您不拥有它们,甚至没有分配它们。

If the method that returned you the object does not explicitly state that it returns a "new", "retain"ed, "alloc"ed, "created" or "copy"-ied object, you must not release it. It's that simple.

So do a release (or autorelease) only for cases like

[object retain];
[object copy];
[SomeClass newInstanceWithProperty: @"a"];
[[SomeClass alloc] initWithProperty: @"a"];

etc.

So in this case, you don't have to do anything and the "release" you mention would crash your app in all likelihood.

What will happen with [keysFromQuery objectAtIndex:0] if I do: [category release];? You shouldn't do that, because it is an autoreleased object.

What will happen with category if I do after that: [keysFromQuery release];? The NSString is still saved, when you release keysFromQuery after the initialization.

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