0

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

3 Answers 3

2

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];
Sign up to request clarification or add additional context in comments.

8 Comments

Or, if you want an autoreleased array then remove the init line, and keep the arrayWithCapacity.
Hi, thanks. Now I am not getting a crash at that point. But as I access the object that I just retrieved from the array. I am getting the following in my debugger: Program received signal: “EXC_BAD_ACCESS”. Could it be NSMutableArray related?
it means that there is another bug somewhere else. you're probably over-releasing an object, that you added to array.
Can you please give me an example of how I could be overreleasing an object?
This is how i am populating that array:
|
2

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];
}
}

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.