将nil添加到NSMutableArray

时间:2010-06-08 14:19:08

标签: objective-c iphone-sdk-3.0 nsmutablearray

我正在尝试通过读取.txt文件来创建NSMutableArray,并且无法将数组的最后一个元素设置为nil。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"namelist" ofType:@"txt"];
NSString *data = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *list = [data componentsSeparatedByString:@"\n"];
NSMutableArray *mutableList = [[NSMutableArray alloc] initWithArray:list];

我想使用NSMutableArray的函数addObject,但这不允许我添加nil。我也尝试过:

[mutableList addObject:[NSNull null]];

但这似乎也不起作用。有没有解决这个问题的方法?

2 个答案:

答案 0 :(得分:0)

Per Apple关于NSMutableArray的文档。

addObject:

Inserts a given object at the end of the receiver.

- (void)addObject:(id)anObject
Parameters

anObject

    The object to add to the end of the receiver's content. **This value must not be nil.**

参考

http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html

答案 1 :(得分:0)

使用

NSMutableArray *mutableList = [[NSMutableArray alloc] init];
[mutableList addObjectsFromArray:list];

希望这会有所帮助 jrtc27