This question already has answers here:
Why NSMutableDictionary don't want write to file?

(2 个回答)


7年前关闭。




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

我设法在我的 Plist 上只写了一对(对象/键)字典(例如:setObject:itemProperties[0] forKey[0])。但我希望添加所有对象和键。到目前为止我还没有完成(返回错误)。有什么帮助吗?
 // 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");
}

最佳答案

您是否正确使用了有效的键和值?



引用:writeToFile:atomically:

关于ios - writeToFile 不适用于 NSDictionary,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18652428/

10-09 09:37