2011-02-09 96 views
-1

如何在另一个类中使用NSMutable Dictionary来读取和写入iphone中plist文件的数据....NSMutableDictionary

任何想法?

回答

1

正如你在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是你的目标路径。

+0

Bermardi感谢您的帮助.. – donkarai 2011-03-14 09:20:40

0

请参阅此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]; 
+0

感谢您的回复... – donkarai 2011-03-14 09:21:57