向NSMutableArray中添加NSInteger对象

7

我有一个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个回答

9

@Omz: 是正确的。确保你已经分配并初始化了数组。请检查以下代码:

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

我已经检查过了,这个方法是可以使用的。 如果不再需要该array,请确保你release掉它。

对于像我这样的新手,要将NSNumber转换回NSInteger(从数组中检索信息),请使用'NSInteger num = [number integerValue];'(感谢7KV7)。 - tmr

4

你没有初始化你的数组,因此当你试图添加到它时,它仍然是 nil

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

2
您还没有初始化响应数组。在您的代码中,可能是在viewDidLoad中,请执行以下操作:
reponses = [[NSMutableArray alloc] init];

然后将该对象添加到您的数组中。
NSInteger val2 = [indexPath row];
[self.reponses addObject:[NSNumber numberWithInteger:val2]];

那应该可以。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接