Aditya
Aditya

Reputation: 21

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?

Upvotes: 2

Views: 9494

Answers (3)

niveuseverto
niveuseverto

Reputation: 280

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

Upvotes: 0

Martin Babacaev
Martin Babacaev

Reputation: 6280

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

Upvotes: 4

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181460

Yes. The rule is, if you retain an object, you are also responsible of releasing it in iOS.

Upvotes: 0

Related Questions