[英]Error writing to plist in documents directory
我使用以下代碼將Resources plist文件復制到documents目錄中:
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Test-Info.plist"];
success = [fileManager fileExistsAtPath:filePath];
if (!success) {
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"Test-Info.plist"];
success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
NSLog(@"Test-Info.plist successfully copied to DocumentsDirectory.");
}
我得到了成功的消息,這很棒。 我假設它已被正確復制到文檔文件夾中。
但是,當我嘗試讀取和寫入保存的plist文件時,它返回null:
Test-Info.plist中的鍵輸入:
Key: EnableEverything
Type: Boolean
Value: YES
編寫代碼:
NSString *adKey = @"EnableEverything";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"Test-Info.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
NSString *enableEverything = [[plist valueForKey:adKey] stringValue];
NSLog(@"****** EXISTING: %@ ******", enableEverything); // returns (null)
// Disable in plist.
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?
NSString *enableEverything1 = [[plist valueForKey:adKey] stringValue];
NSLog(@"****** NOW: %@ ******", enableEverything1); // returns (null)
輸出:
****** EXISTING: (null) ******
****** NOW: (null) ******
我的問題是為什么它們(null)
存在於plist文件中?
您正在嘗試改變不可變對象。
你需要一個NSMutableDictionary 。
IE
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile: path] mutableCopy];
同時檢查plist對象是否為零,因為任何消息都可以發送到nil而不會出現錯誤。 這不會失敗,也沒有實際發生。
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?
由於源路徑為nil,因此您最好不要在
編譯
捆綁期間復制文件。 把它拖到這里:
嘗試使用nsbundle資源路徑
NSString *path= [[NSBundle mainBundle] pathForResource:@"SportsLogo-Info" ofType:@"plist"];
嘗試分配
NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:path]];
還要檢查文件是否已被復制。 轉到Library => Application Support => iPhone Simulator =>名為你的模擬器版本的文件夾iOS => Applications =>查找項目的正確文件夾=>文件查看plist文件是否在那里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.