Franky
Franky

Reputation: 912

Crash Using insertObject in NSMutableArray

I have a NSMUtableArray where I want to insert at different index and in different method some data. So I initialize my NSMutableArray in my viewDidLoad like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    params=[[NSMutableArray alloc]init];
    params =[NSMutableArray arrayWithCapacity:20];
    for (int i = 0; i<20; i++) {

        [params addObject:[NSNull null]];
    }

}

And in different method I try to replace the null value by the real value:

-(void)doInBackGround{

    NSString * domaine=@"Toto";
    int port =8080;

    [params replaceObjectAtIndex:8 withObject:domaine];

    [params replaceObjectAtIndex:9 withObject:[NSString stringWithFormat:@"%d",nbPort]];

}

Another method where I try to replace the value in the NSMutableArray "params"

-(void)someMethod{

    NSString * computer=@"Ajax";
    int port =3333;

    [params replaceObjectAtIndex:4 withObject:computer];

    [params replaceObjectAtIndex:5 withObject:[NSString stringWithFormat:@"%d",nbPort]];

}

But I have a crash in line where I try to replace the Object:

[params replaceObjectAtIndex:8 withObject:domaine];

How can I fix It?. I think that my problem is where I intialize the NSMUtableArray? What do you think?

Upvotes: 0

Views: 1450

Answers (2)

Leon
Leon

Reputation: 410

First initialise your params ivar before you do any modification on it.

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.loginValidated =NO;
    NSLog(@"Affichage Login Form");

  params = [[NSMutableArray arrayWithCapacity:20] retain]; 
   // params =[NSMutableArray arrayWithCapacity:20];
    for (int i = 0; i<20; i++) {

        [params addObject:[NSNull null]];
    }

    // Do any additional setup after loading the view from its nib.

   [self performSelectorInBackground:@selector(doInBackGround) withObject:nil];
}

And as an extra tip for your doInBackground so you can prevent unrecognised selector issues:

-(void)doInBackGround{

    NSString * domaine=@"Toto";
    int nbPort =8080;

    if(params){
       [params replaceObjectAtIndex:8 withObject:domaine];
       [params replaceObjectAtIndex:9 withObject:[NSString stringWithFormat:@"%d",nbPort]];
   }
}

Upvotes: 0

omz
omz

Reputation: 53561

First off, you're initializing params twice, the first one is entirely superfluous, as you're never doing anything with the empty array.

Your second initialization, using arrayWithCapacity: returns an autoreleased object, so by the time you're trying to replace objects in it, it has likely been deallocated.

Familiarize yourself with some memory management basics and use a retained property for the array. You might also want to switch to using ARC (automatic reference counting), which makes this kind of error less likely (though it's still helpful to know about memory management).

Upvotes: 2

Related Questions