我一直在試圖實現在is it possible to save NSMutableArray or NSDictionary data as file in iOS?給出的答案,他們一直沒有爲我工作。有人會告訴我我做錯了什麼嗎?我的NSArray是一個自定義對象,例如Cat
。貓本身是由字符串和數字組成的。這裏是我的代碼如何保存NSArray並從文件中檢索NSArray
-(void)saveArrayToFile:(NSArray *)response;
{
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSString *filePath = [documentsDirectory stringByAppendingPathComponent:PERSISTENT_FILENAME];
//
// [response writeToFile:filePath atomically:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
if ([paths count] > 0)
{
// Path to save array data
NSString *arrayPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"array.out"];
// Write array
[response writeToFile:arrayPath atomically:YES];
}else NSLog(@"NO paths");
}
-(NSArray *)getArrayFromFile
{
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSString *filePath = [documentsDirectory stringByAppendingPathComponent:PERSISTENT_FILENAME];
// return [NSArray arrayWithContentsOfFile:filePath];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
if ([paths count] > 0)
{
// Path to save array data
NSString *arrayPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"array.out"];
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
return arrayFromFile;
}else NSLog(@"No file to retrieve");
return nil;
}
首先我嘗試了註釋的代碼。然後我嘗試了另一個。目前的問題是文件沒有被保存。
什麼的'NSArray的必須是一個有效的屬性lists'是什麼意思?我的數組是自定義對象的集合。該對象本身有字符串和數字。 – 2014-09-11 01:47:22
爲什麼你認爲提供的代碼不起作用?當你運行它時發生了什麼? – Jonah 2014-09-11 01:54:22
屬性列表對象在https://developer.apple.com/library/mac/documentation/general/conceptual/devpedia-cocoacore/PropertyList.html – Jonah 2014-09-11 01:56:42