将NSInteger对象添加到NSMutableArray

时间:2011-12-22 07:51:50

标签: iphone objective-c cocoa-touch nsmutablearray nsinteger

我有一个NSMutableArray

@interface DetailViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {

NSMutableArray *reponses;
}
@property (nonatomic, retain) NSMutableArray *reponses;

@end

我正在尝试添加我的数组NSInteger对象:

@synthesize reponses;



NSInteger val2 = [indexPath row];
[reponses addObject:[NSNumber numberWithInteger:val2]];
NSLog(@"the array is %@ and the value is %i",reponses, val2);

无法将对象添加到数组中,这就是控制台显示的内容:

the array is (null) and the value is 2

3 个答案:

答案 0 :(得分:8)

@Omz:是的。确保已分配和初始化阵列。请检查以下代码

NSMutableArray *array = [[NSMutableArray alloc] init];
NSInteger num = 7;
NSNumber *number = [NSNumber numberWithInt:num];
[ar addObject:number];
NSLog(@"Array %@",array);

我检查了这个并且它有效。 如果不再需要array,请确保release

答案 1 :(得分:4)

您尚未初始化阵列,因此当您尝试添加阵列时,它仍为nil

self.responses = [NSMutableArray array];
//now you can add to it.

答案 2 :(得分:1)

您尚未初始化响应数组。在您的代码中,可能是viewDidLoad,执行:

reponses = [[NSMutableArray alloc] init];

然后将对象添加到数组中。

NSInteger val2 = [indexPath row];
[self.reponses addObject:[NSNumber numberWithInteger:val2]];

这应该有效。