pchap10k
pchap10k

Reputation: 2076

Having trouble adding objects to NSMutableArray in Objective C

I am using the iPhone SDK and have an issue doing something simple. I am trying to add an NSNumber object to an NSMutableArray instance variable. I tried adding NSNumber card to NSMutableArray viewedCardsArray, however without breaking, it does not get added to the array. Here is the code.


/////////////////////////////////////////////////////
// Inside the header file Class.h
@interface MyViewController : UIViewController {
   NSMutableArray *viewedCardsArray;
   //snip ...
}
@property (nonatomic, retain) NSMutableArray *viewedCardsArray;
@end

/////////////////////////////////////////////////////
// Inside the methods file Class.m
#import "StudyViewController.h"

@implementation StudyViewController
@synthesize viewedCardsArray
  //snip ...

- (IBAction)doShowCard {
   //snip ...
   NSNumber *cardIdObject = [[NSNumber alloc] initWithInt:(int)[self.currentCard cardId]];
   [viewedCardsArray addObject: cardIdObject];
   [cardIdObject release];
}

So this code executes, and does not seem to leak (according to the Leaks performance tool). However when stepping through the code, at no point does CardIdObject appear in viewedCardsArray.

Looking through SO, I know these basic questions are pretty common to ObjC newbies (like me) so apologies in advance!

Upvotes: 1

Views: 16225

Answers (2)

Alastair Stuart
Alastair Stuart

Reputation: 4185

Perspx has outlined one way of initializing the array. However, you can also use the class methods provided by NSArray:

self. viewedCardsArray = [NSMutableArray array];

This can go in init or elsewhere.

Note: The object will be autoreleased.

Upvotes: 3

Alex Rozanski
Alex Rozanski

Reputation: 38005

Have you initialized your viewedCardsArray? If not you need to somewhere - this is usually done in the init method for your class:

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

Then it is released in the dealloc method:

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

Upvotes: 17

Related Questions