Steve
Steve

Reputation: 19

NSMutableArray object not accessible in methods

I have the following variable in my .h file:

NSMutableArray *arr;

Then I have a method in implementation:

void aMethod
{
    if (something)
    {
        arr= [[NSMutableArray alloc] init];
    arr = [NSMutableArray arrayWithCapacity:0]; 
        [arr addObject:someObject];
    }

now if I try to access arr from any other method or even another if block within the same method, the app crashes and I can't access that arr. For example:

  //same method:
  if (something else)
  {
       SomeObject *obj = [arr objectAtIndex:0]; //<---- it crashes on this line
  }

Any light guys? Thanks in advance

Upvotes: 0

Views: 291

Answers (3)

Seva Alekseyev
Seva Alekseyev

Reputation: 61396

You're constructing the array twice. The following two lines:

arr= [[NSMutableArray alloc] init];
arr = [NSMutableArray arrayWithCapacity:0];  

The first one constructs an empty array. The second one throws away the results of the first line, and constructs another empty array that is autoreleased - that is, does not live beyond the current method unless explicitly retained.

Wipe the arrayWithCapacity line, it'll work as expected. Don't forget to release in dealloc.

Upvotes: 2

Warren Burton
Warren Burton

Reputation: 17378

The second init of the array forms an auto released instance.

Do this

-(id)init
{
self = [super init];
if(self)
{
   arr = [[NSMutableArray arrayWithCapacity:5] retain];
}
return self;
}

-(void)dealloc
{
[arr release];
[super dealloc];
}

-(void)aMethod
{
if (something)
{     
   [arr addObject:someObject];
}
}

Upvotes: 2

Max
Max

Reputation: 16709

There are 2 errors here:

  1. You have a leak

    arr= [[NSMutableArray alloc] init]; //<--here

  2. it crashes cause you're creating autoreleased object and then try to access it when it is already deallocated:

    arr = [NSMutableArray arrayWithCapacity:0];

remove this line:

arr = [NSMutableArray arrayWithCapacity:0];

Upvotes: 2

Related Questions