Obj-c autorelease a variable up a chain of methods

纵然是瞬间 提交于 2020-01-06 07:27:11

问题


I'm new to Obj-C and I have a question concerning the autorelease. Is it ok to return an autoreleased variable for several methods? For example:

- (void) methodC {
    Object anObj = [self methodB];
    //Do something with anObj
}

- (Object *) methodB {
    return [self methodA];
}   

- (Object *) methodA {
    Object anObj = [[anObj alloc] init];
    release [anObj autorelease];  
}

Will the variable remain valid even if it is returned up a method chain and used at the top? Or does it have to be retained somewhere along the way?

thank you


回答1:


Yes, it will be valid in this case. You only have to worry about the variable being deallocated if somebody drains the autorelease pool. As long as you've written every function that returns along the way and you don't explicitly drain the autorelease pool, you don't have to worry about objects being deallocated from under you.

In the vast majority of cases, the code in the NSRunLoop takes care of draining the autorelease pool. When you return control from your application code to the API code (such as by returning from a touchesBegan handler etc.), you don't know if the autorelease pool will be drained, so you have to assume in the worst case that it will. In that case, you have to retain any objects you want to keep references to.

For example:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

Object *anObj = [self methodC];  // Your methodC as before -- anObj is valid

[pool drain];  // anObj will be deallocated here



回答2:


The variable should remain valid. You only need to retain an object if it is actually "owned" by some other object and could be indirectly/unintentionally released along with it. For example, if you extracted an object from an array and then released the array, your object reference could become invalid unless you explicitly retain it.

For more details, see Object Ownership and Dismissal, particularly the sections on Autorelease and Validity of Shared Objects. The latter uses the following code to illustrate how you could "accidentally" make an object reference invalid.

heisenObject = [array objectAtIndex:n];

[array removeObjectAtIndex:n];

// heisenObject could now be invalid.

The following code shows how to mitigate this problem using retain.

heisenObject = [[array objectAtIndex:n] retain];

[array removeObjectAtIndex:n];

// use heisenObject.

[heisenObject release];


来源:https://stackoverflow.com/questions/5878875/obj-c-autorelease-a-variable-up-a-chain-of-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!