在 Objective C 中将对象添加到 NSMutableArray 时遇到问题 [英] Having trouble adding objects to NSMutableArray in Objective C

查看:26
本文介绍了在 Objective C 中将对象添加到 NSMutableArray 时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 iPhone SDK,但在做一些简单的事情时遇到了问题.我正在尝试将 NSNumber 对象添加到 NSMutableArray 实例变量.我尝试将 NSNumber card 添加到 NSMutableArray viewedCardsArray,但是没有中断,它不会被添加到数组中.这是代码.

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

所以这段代码执行了,并且好像没有泄漏(根据Leaks性能工具).但是,在单步执行代码时,CardIdObject 不会出现在 viewedCardsArray 中.

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.

通过 SO,我知道这些基本问题对于 ObjC 新手(像我一样)很常见,所以提前道歉!

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

推荐答案

您是否已初始化您的 viewedCardsArray?如果不是,您需要在某个地方 - 这通常在您的类的 init 方法中完成:

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

然后在dealloc方法中释放:

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

这篇关于在 Objective C 中将对象添加到 NSMutableArray 时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆