【发布时间】:2011-02-09 13:16:36
【问题描述】:
如何在另一个类中使用 NSMutable Dictionary 从 iphone 中的 plist 文件中读取和写入数据....
有什么想法吗?
【问题讨论】:
标签: iphone
如何在另一个类中使用 NSMutable Dictionary 从 iphone 中的 plist 文件中读取和写入数据....
有什么想法吗?
【问题讨论】:
标签: iphone
你可以在NSDictionary reference 中找到,这个类有一个从文件initWithContentsOfFile:(NSString *)path 创建一个nsdictionary 的方法。您可以执行以下操作:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"myDictionary" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
myDictionary 是您的 plist 名称(如果您的 plist 在资源包中)。 您可以使用以下方法在磁盘上写入 plist:
[dict writeToFile:filePath atomically: YES];
filePath 是您的目标路径。
【讨论】:
请参阅tutorial 上的 Plist 文件示例。
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.plist", plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:plistName ofType:@"plist"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath
stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];
【讨论】: