Objective C autorelease
Hello I do not fully understand the autorelease function call in obj-C.
@interface A{
id obj;
}
@implementation A
-(void)myMethod;
{
obj = [BaseObj newObj]; //where newObj is a method like :[[[BaseObj alloc]init]autorelease];
}
-(void)anotherMehtod;
{
[obj someMeth]; //this sometimes gives me EXC_BAD_ACCESS
}
@end
So to solve this I put a开发者_开发问答 retain. Now do I need to release this object manually if i retain it?
If you are the owner of an object - is your responsibility to release it.
You become owner of an object if you've done at least one of the following:
- instantiated it through
alloc
- passed
retain
- passed
copy
For more details read Object Ownership and Disposal
Yes. The rule is, if you retain an object, you are also responsible of releasing it in iOS.
Like all other static methods in Obj-C [BaseObj newObj]
only exists in your method -(void)myMethod
at the end of this method (roughly) obj
gets -release
message from autorelease pool.
If you want to preserve this object - use [[BaseObj newObj] retain]
or [BaseObj alloc] init]
and release it in -dealloc
or when you has to.
For example:
@interface A{
id obj;
}
@implementation A
-(void)myMethod
{
[obj autorelease];
obj = [[BaseObj newObj] retain]; //where newObj is a method like :[[[BaseObj alloc]init]autorelease];
}
-(void)anotherMehtod;
{
[obj someMeth]; //this sometimes gives me EXC_BAD_ACCESS
}
-(void)dealloc
{
[obj release];
[super dealloc];
}
@end
精彩评论