【问题标题】:Write NSMutableArray to plist not working将 NSMutableArray 写入 plist 不起作用
【发布时间】:2012-08-25 12:48:17
【问题描述】:

我正在使用 plists 来保存/加载 NSMutableArray,

代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *prsPath = [documentsDirectory stringByAppendingPathComponent:@"records.plist"];

prs = [[NSMutableArray alloc] initWithContentsOfFile:prsPath];

当我在代码的其他地方使用最后一句代码时,它会显示:“prsPath”未声明。 (我在 ViewDidLoad 中加载我的代码)当我添加一个对象时,它不会保存它,它甚至不会显示出来。 (加载最后一句添加)

【问题讨论】:

  • 你的问题不清楚。您正在显示用于阅读的代码,在标题中它说写作不起作用。在文本中,您解决了一个未声明的变量问题(完全不同)。

标签: objective-c nsmutablearray plist


【解决方案1】:

我正在使用这种方法,它的工作效率是 100%

- (void) writeToPlist: (NSString*)fileName withData:(NSMutableArray *)data
{
     NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
     NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:fileName];

     [data writeToFile:finalPath atomically: YES];
     /* This would change the firmware version in the plist to 1.1.1 by initing the NSDictionary with the plist, then changing the value of the string in the key "ProductVersion" to what you specified */
}

还有这个从plist文件中读取的方法:

- (NSMutableArray *) readFromPlist: (NSString *)fileName {
     NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
     NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:fileName];

     BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:finalPath];

     if (fileExists) {
          NSMutableArray *arr = [[NSMutableArray alloc] initWithContentsOfFile:finalPath];
          return arr;
     } else {
          return nil;
     }
}

希望对你有帮助。

【讨论】:

    【解决方案2】:

    [[NSMutableArray alloc] initWithContentsOfFile:prsPath]加载一个 plist ant 用它来初始化一个数组。您 plist 是否已经存在于该路径中?您可能还想记录 prsPath 以查看它是否正确。

    通常您会首先通过调用[[NSFileManager defaultManager] fileExistsAtPath:prsPath] 来检查路径中是否存在plist。如果没有,则初始化一个空数组。

    稍后您通过调用[prs writeToFile:prsPath atomically:YES] 保存它。

    请注意,您不能从 plist 初始化 NSMutableArrays。从 plist 加载的数组和字典始终是不可变的。您必须首先将 plist 加载到 NSArray 中,然后从该 NSArray 初始化 NSMutableArray

    【讨论】:

    • 如果我在 ViewDidLoad 中使用 NSLog,它会起作用,但是当我在代码中的其他地方使用 NSLog 时,它会给出未声明。
    • 嗯,prsPath 是视图控制器的强/保留属性吗?
    • ;/ 开玩笑的,我真的忘记了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多