Having trouble adding objects to NSMutableArray in

2018-12-31 19:17发布

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!

2条回答
泛滥B
2楼-- · 2018-12-31 19:50

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.

查看更多
忆尘夕之涩
3楼-- · 2018-12-31 19:53

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];
}
查看更多
登录 后发表回答