2010-04-27 39 views

回答

2

如果您的數組或字典僅包含字符串,日期,數字,數組和字典等「標準」數據類型,則可以使用-[NSArray writeToFile:atomically:]-[NSDictionary writeToFile:atomically:]將內容保存到.plist文件。要讀取文件,請使用-initWithContentsOfFile:

請注意,應用程序捆綁在iPhone OS設備上不可寫,因此您必須將該文件存儲在應用程序的Documents目錄中。

1

此解決方案可應用於NSArrayNSDictionary

使用此方法從屬性列表中創建一個NSData,並使用writeToFile將其保存到磁盤。

[NSPropertyListSerialization dataFromPropertyList:(id)plist 
              format:(NSPropertyListFormat)format 
           errorDescription:(NSString **)errorString]; 

使用此方法從NSData讀取屬性列表。

[NSPropertyListSerialization propertyListFromData:(NSData *)data 
           mutabilityOption:(NSPropertyListMutabilityOptions)opt 
              format:(NSPropertyListFormat *)format 
           errorDescription:(NSString **)errorString]; 

實施例:

NSPropertyListFormat format = 0; 
NSString *errorString = nil; 

NSDictionary *dataDict = [NSPropertyListSerialization propertyListFromData:data 
     mutabilityOption:NSPropertyListMutableContainersAndLeaves 
     format:&format errorDescription:&errorString]; 

if (errorString != nil) { 
    NSLog(errorString); 
    [errorString release]; 
} 

NSLog(@"got dictionary:%@", dataDict); 

errorString = nil; 
NSData *data = [NSPropertyListSerialization dataFromPropertyList:dataDict 
     format:NSPropertyListXMLFormat_v1_0 errorDescription:errorString]; 

NSLog(@"plist data:%@", data); // convert to NSString to get <plist>