2011-11-01 61 views
2

我一直在試圖將數據寫回到我的包中的預定義plist文件(data.plist)。使用下面的代碼,我調用例程'dictionaryFromPlist'來打開文件,然後調用'writeDictionaryToPlist'來寫入plist文件。但是,沒有數據被添加到plist文件。將數據添加到plist文件的問題

NSDictionary *dict = [self dictionaryFromPlist]; 

NSString *key = @"Reports"; 
NSString *value = @"TestingTesting"; 
[dict setValue:value forKey:key]; 

[self writeDictionaryToPlist:dict]; 


- (NSMutableDictionary*)dictionaryFromPlist { 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; 
    NSMutableDictionary* propertyListValues = [[NSMutableDictionary alloc]  
    initWithContentsOfFile:filePath]; 
    return [propertyListValues autorelease]; 
} 

- (BOOL)writeDictionaryToPlist:(NSDictionary*)plistDict{ 
    NSString *filePath = @"data.plist"; 
    BOOL result = [plistDict writeToFile:filePath atomically:YES]; 
    return result; 
} 

代碼成功運行,沒有錯誤拋出,但沒有數據添加到我的plist文件。

回答

1

正如@logancautrell你不能在mainbundle寫提到的,你可以保存在應用程序文件夾你的plist中,你可以這樣做:

NSString *path = @"example.plist"; 
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *basePath = ([paths count]> 0)? [paths objectAtIndex: 0]: nil; 
NSString *documentPath = [basePath stringByAppendingPathComponent:path] // Documents 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
BOOL checkfile = [fileManager fileExistsAtPath: documentPath]; 
NSLog(@"%@", (checkFile ? @"Exist": @"Not exist"));//check if exist 
if(!checkfile) {//if not exist 
    BOOL copyFileToDoc = [yourDictionary writeToFile:documentPath atomically: YES]; 
    NSLog(@"%@",(copyFileToDoc ? @"Copied": @"Not copied")); 
    } 
+0

謝謝兩位,上面的代碼工作完美。 – user616076

2

您不能寫入您的軟件包,它是隻讀的。如果你的情況,你正在寫一個相對路徑,而不是捆綁。

我不確定iOS應用程序的默認工作目錄是什麼。最好使用絕對路徑。您應該寫入文檔/緩存目錄。像這樣的東西將得到你的道路:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

然後只是抓住lastObject並將其前置到您的文件名。