我正在尝试将NSMutableArray
保存到预先存在的plist中。
当我尝试:
NSError *errorDesc;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:@"Array_Label_Generiche.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
NSLog(@"prima volta");
plistPath = [[NSBundle mainBundle] pathForResource:@"Array_Label_Generiche" ofType:@"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSMutableArray *temp = (NSMutableArray *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!temp) {
NSLog(@"Error reading plist: %@, format: %lu", errorDesc, format);
}
contatore = (int)temp.count ;
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
[dictionary setObject:array_copiato forKey:[NSString stringWithFormat: @"%@", [alertView textFieldAtIndex:0].text]];
NSDictionary *dictionary_da_salvare = [[NSDictionary alloc ] initWithDictionary: dictionary];
//AGGIUNGO I DATI CREATI
NSLog(@"TEMP %@",temp);
[temp addObject:dictionary_da_salvare];
BOOL didWriteArray = [temp writeToFile:plistPath atomically:YES];
if (didWriteArray)
{
NSLog(@"Write to .plist file is a SUCCESS!");
}
else
{
NSLog(@"Write to .plist file is a FAILURE!");
}
在这种情况下,输出显示“写入.plist文件是FAILURE!”。
在Apple指南中,我读到在写入plist之前我必须序列化数据。
然后我尝试编写这些代码行:
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:temp format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];
if(plistData == nil){
NSLog (@"error writing to file: %@", errorDesc);
}
当我运行应用程序时,输出区域显示为:
写入文件时出错:属性列表格式无效(属性 列表不能包含'CFType'类型的对象。)写入.plist文件 是一个失败!
我认为因为数组测试是NSMutableArray,因为我已阅读Apple指南:
NSPropertyListSerialization类提供转换的方法 属性列表与几种序列化格式之间的对象。属性 列表对象包括NSData,NSString,NSArray,NSDictionary,NSDate, 和NSNumber对象。这些物体与他们的免费桥接 各自的Core Foundation类型(CFData,CFString等)。