writeToFile无法与NSDictionary工作

我环顾了其他类似的问题,但没有真正起作用。

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

// 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"); } 

你有没有正确使用有效的键和值?

在写出文件之前,此方法recursion地validation所有包含的对象是属性列表对象(NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary的实例),如果所有对象不是属性列表对象,则返回NO生成的文件不会是有效的属性列表。

引用: writeToFile:primefaces地:

你无法控制你有时要写的内容。 例如,当您要编写从服务器获取的JSON对象时,您无法避免使用null值。

NSData与这些“无效”值兼容,所以在这种情况下将NSArrayNSDictionary转换为NSData是一种理想的方法。

写:

 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:jsonObject]; [data writeToFile:path atomically:YES]; 

读:

 NSData *data = [NSData dataWithContentsOfFile:path]; NSDictionary *jsonObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];