writeToFile无法使用NSDictionary [英] writeToFile not working with NSDictionary

查看:108
本文介绍了writeToFile无法使用NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾了其他类似的问题,但没有真正奏效。

I looked around other similar questions about this but nothing really worked.

我设法在我的Plist上只编写了一对字典对(对象/键)(例如:setObject:itemProperties [0] forKey [0])。但我希望添加所有的对象和密钥。到目前为止我没有管理(返回错误)。任何帮助?

I managed to write only one pair (object / key) of the dictionary (e.g.: setObject:itemProperties[0] forKey[0]) on my Plist. But I would like all the objets and keys to be added. I didn't managed so far (return the error). Any help?

 // Path to Documents Folder

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"items.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"items.plist"] ];
}

NSMutableDictionary *items;

if ([fileManager fileExistsAtPath: path])
{
    items = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
}
else
{
    // If the file doesn’t exist, create an empty dictionary
    items = [[NSMutableDictionary alloc] initWithCapacity:5];
}

// array of the item properties
NSArray *itemProperties = @[myItem.itemTitle, myItem.itemImage, myItem.itemPositionX, myItem.itemPositionY, myItem.itemHeight, myItem.itemWidth];

// Set the key values for each field    
NSArray *keys = @[@"Title", @"Image", @"PositionX", @"PositionY", @"Height", @"Width"];


[items setObject:itemProperties forKey:keys];

//Save dictionnary to Plist
[items writeToFile: path atomically:YES];

if (![items writeToFile:path atomically:YES]) {
    NSLog(@"Error with creating Plist");
}


推荐答案

您是否正确使用了有效密钥? &安培;值?

Have you properly use valid keys & values ?


此方法递归验证所有包含的对象是
属性列表对象(NSData,NSDate,NSNumber,
NSString,NSArray或NSDictionary)在写出文件之前,如果所有对象都不是属性列表对象,则
返回NO,因为
结果文件不是有效的属性列表。

This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

参考: writeToFile:atomically:

这篇关于writeToFile无法使用NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆