2012-05-23 100 views
1

我想寫一個非常簡單的數據到.plist文件,我已經檢查了各種代碼示例,但我很掙扎讓它起作用。試圖寫入.plist文件,但它不起作用

首先,有創建該文件本身並返回路徑的方法:

-(NSString *)getFilePath{ 
    NSArray *thePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    return [[thePath objectAtIndex:0] stringByAppendingPathComponent:@"events.plist"]; 
} 

然後,這是我已經迷上了一個按鈕的動作。它現在只插入一行虛擬數據。或者至少,這就是我想要做的。

- (IBAction)saveData:(id)sender { 
    NSArray *data = [[NSArray alloc] initWithObjects:@"E3 Expo", @"05-06-2012", nil]; 
    [data writeToFile:[self getFilePath] atomically:YES]; 
} 

但它不起作用。我通過Xcode中的管理器檢查了用戶文檔的目錄,並且沒有在「文檔」文件夾中創建任何內容。

任何幫助,將不勝感激。 :)

+0

的Plist是NSDictionarys ... – CodaFi

回答

0

您必須將字典設置爲root plist對象。

[編輯:如果您看不到文件,用NSFileManager創建]

NSError *error; 
NSString *plistPath = [self getFilePath]; 

NSArray *data = [[NSArray alloc] initWithObjects:@"E3 Expo", @"05-06-2012", nil]; 
NSDictionary *plistDict = [NSDictionary dictionaryWithObject: data forKey: @"array"]; 
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict 
                   format:NSPropertyListXMLFormat_v1_0 
                errorDescription:&error]; 
if(plistData) { 
    //not necessary 
    if ([[NSFileManager defaultManager] fileExistsAtPath: plistPath]) { 
     [[NSFileManager defaultManager] removeItemAtPath: plistPath error: &error]; 
    } 
    [[NSFileManager defaultManager] createFileAtPath: plistPath contents:plistData attributes: nil]; 
    //necessary 
    [plistData writeToFile: plistPath atomically:YES]; 
} 
else { 
    NSLog(error); 
    [error release]; 
} 
//also release data, since you retained it (sorry, memory management OCD) 
[data release]; 

Based on Apple documentation - scroll to Write Out the Property List

+0

它不工作。所有的代碼都在執行,但Documents目錄仍然是完全空的。 – user1191304

+1

這不會是一個適當的plist,但它應該工作。從[writeToFile:atomically:](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/writeToFile :atomically :):如果數組的內容全部是屬性列表對象(NSString,NSData,NSArray或NSDictionary對象),則可以使用此方法編寫的文件用類方法arrayWithContentsOfFile初始化新數組:或者實例方法initWithContentsOfFile :. –

+0

請參閱編輯答案,但我沒有發現需要使用NSFileManager創建文件。我測試了它並使用iExplorer檢索了該文件,似乎沒有問題。 –

相關問題