[英]Having trouble adding objects to NSMutableArray in Objective C
I am using the iPhone SDK and have an issue doing something simple. 我正在使用iPhone SDK,在做一些简单的事情时遇到了问题。 I am trying to add an NSNumber object to an NSMutableArray instance variable.
我正在尝试将NSNumber对象添加到NSMutableArray实例变量。 I tried adding NSNumber card to NSMutableArray viewedCardsArray , however without breaking, it does not get added to the array.
我尝试将NSNumber 卡添加到NSMutableArray visibleCardsArray ,但是不中断,它不会添加到数组中。 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). 因此此代码将执行,并且似乎不会泄漏(根据Leaks性能工具)。 However when stepping through the code, at no point does CardIdObject appear in viewedCardsArray .
但是,单步执行代码时, CardIdObject绝不会出现在viewedCardsArray中 。
Looking through SO, I know these basic questions are pretty common to ObjC newbies (like me) so apologies in advance! 从SO的角度来看,我知道这些基本问题对于ObjC新手(像我一样)非常普遍,因此请您提前道歉!
Have you initialized your viewedCardsArray
? 您是否初始化了
viewedCardsArray
? If not you need to somewhere - this is usually done in the init
method for your class: 如果不需要,则需要在某处-通常是在类的
init
方法中完成的:
- (id)init
{
self = [super init];
if(self) {
viewedCardsArray = [[NSMutableArray alloc] init];
}
return self;
}
Then it is released in the dealloc
method: 然后在
dealloc
方法中释放它:
- (void)dealloc
{
[viewedCardsArray release];
[super dealloc];
}
Perspx has outlined one way of initializing the array. Perspx概述了初始化数组的一种方法。 However, you can also use the class methods provided by NSArray:
但是,您也可以使用NSArray提供的类方法:
self. viewedCardsArray = [NSMutableArray array];
This can go in init or elsewhere. 这可以在init或其他地方进行。
Note: The object will be autoreleased. 注意:该对象将被自动释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.