问题描述
我一直不使用plists,因为我不知道如何使用plist。
I've always refrained from using plists as I'm not really sure how to use one.
任何人都可以给一个简单的使用plist的代码示例?我有兴趣将一个 NSArray
或 NSDictionary
保存到plist,然后再次检索它。
Could anyone give a simple code example of using a plist? I'm interested in saving an NSArray
or NSDictionary
to a plist and then retrieving it again later.
存储 NSArray
或 NSDictionary
?
推荐答案
您可以存储以下数据类型作为值:
You can store the following data types in a .plist file as value:
- NSArray
- NSMutableArray
- NSDictionary
- NSMutableDictionary
- NSData
- NSMutableData
- NSString
- NSMutableString
- NSNumber
- NSDate
- NSArray
- NSMutableArray
- NSDictionary
- NSMutableDictionary
- NSData
- NSMutableData
- NSString
- NSMutableString
- NSNumber
- NSDate
使用NSDictionary,您可以将由某些键值对组成的关联数组存储在plist中。
With an NSDictionary you can store in a plist an associative array composed by some key-value pair. Use the NSArray if you only want to save a data series.
要在plist文件中保存上面的对象,只需写下:
To save one of the object above on a plist file simply write:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"yourFileNameHere"];
}
//Write to the plist
[myArray writeToFile:[self dataFilePath] atomically:YES];
//Read from the plist
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
}
这篇关于从Plist存储和检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!