user1165664
user1165664

Reputation: 185

NSMutableArray replaceObjectAtIndex: withObject: Not Working

I have a mutable array that, originally, I was having trouble with the scope. I got some advice on how to fix that (which worked), but now the array will not replace the objects at a given index.

Here is the code:

.h file:

@interface myViewController: UIViewController {
  NSMutableArray *myArray;
}

.m file:

-(id)init {
  self = [super init];
  if (self){
    myArray = [[NSMutableArray alloc] init];
  }
  return self;
}

-(void)viewDidLoad {
  for (int x=0; x<6; x++) {
    [myArray addObject:[NSNumber numberWithInt:0]]; //This adds the numbers just fine
  }
  [myArray insertObject:[NSNumber numberWithInt:1] atIndex:0]; //This does not insert the number 1 into index 0
}

I've tried other ways to insert, such as:

replaceObjectAtIndex: withObject

And some others, but none of them worked....

I would greatly appreciate any help as this is the only thing standing between me and finishing my first app.

Thanks!

Upvotes: 1

Views: 2035

Answers (3)

Ken Thomases
Ken Thomases

Reputation: 90601

The designated initializer for UIViewController is -initWithNibName:bundle:. You should override that rather than -init. Your -init is not getting called, so you are never assigning anything to myArray; it just remains nil.

Upvotes: 0

Tommy V
Tommy V

Reputation: 177

Make sure you call the addSubview of your current view methode before.

YouViewNewController *youViewNewController=[[YouViewNewController alloc]init];

[self.view addSubview:youViewNewController.view]; // Calls viewDidLoad.

this work for me,

-(id)init {
self = [super init];
if (self){
    myArray = [[NSMutableArray alloc] init];
    NSLog(@"Lancement...");
}
return self;

}

-(void)viewDidLoad 
{
   NSLog(@"Calcul...");

   for (int x=0; x<6; x++) 
    {
          [myArray addObject:[NSNumber numberWithInt:0]]; //This adds the numbers just fine
    }
    [myArray insertObject:[NSNumber numberWithInt:1] atIndex:0]; //This does not insert the number 1 into index 0

    NSLog(@"%i", [[myArray objectAtIndex:0]intValue]);
}

it works !

Upvotes: 0

bbum
bbum

Reputation: 162722

First, class names should be capitalized. I say "first" because this indicates that you aren't following convention and that can lead to problems in comprehension, if not flat out bugs.

Secondly, are you sure the init method is being invoked at all? If your object is instantiated by the interface file load, then it likely isn't and the array is likely nil.

Upvotes: 3

Related Questions