【问题标题】:Adding nil to NSMutableArray将 nil 添加到 NSMutableArray
【发布时间】:2010-06-08 14:19:08
【问题描述】:

我正在尝试通过读取 .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]];

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

【问题讨论】:

  • NSNull 方法有什么问题?似乎它旨在准确解决您的问题......为什么您仍然需要最后一个元素为 nil(或 NSNull)?
  • 添加 [NSNull null] 时遇到什么错误?如果你使用这个,它会工作吗:NSMutableArray *mutableList = [list mutableCopy];
  • 我认为 [NSNull null] 可能正在工作(我意识到问题是我试图打印出一个空值,这导致了错误)。这是源于此问题的另一个问题: mutableList.count 返回 0,即使列表中有元素(我什至将其内容打印出来)。这是某种内存管理问题吗?作为 Objective-C 的新手并且来自 Java,这非常令人费解:/

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


【解决方案1】:

使用

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

希望这会有所帮助 jrtc27

【讨论】:

  • 我认为:NSMutableArray *mutableList = [list mutableCopy]; 更好
  • 非常正确 ;) - 没想到。也容易理解很多
【解决方案2】:

根据 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    相关资源
    最近更新 更多