2010-09-28 84 views
0

我正在嘗試將布爾寫入plist文件。我的代碼是:如何將布爾寫入plist文件

NSString *filePath = [self dataFilePath]; 
if (filePath) 
{ 
    if (check) 
    { 
    NSLog(@"Clear"); 
    [item setObject:[NSNumber numberWithBool:NO] forKey:@"check"]; 
    [item writeToFile:filePath atomically: YES]; 
    }else{ 
    NSLog(@"Green"); 
    [item setObject:[NSNumber numberWithBool:YES] forKey:@"check"]; 
    [item writeToFile:filePath atomically: YES]; 
    } 
    NSLog([[NSString alloc] initWithContentsOfFile:filePath]); 
}else{ 
    NSLog(@"write file was not found"); 
} 

我的文件路徑是:

- (NSString *)dataFilePath 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return [documentsDirectory stringByAppendingPathComponent:@"CheckMark.plist"]; 
} 

我加載我的數組:

- (void)viewDidLoad 
{ 
NSString *filePath = [self dataFilePath]; 
NSLog(@"%@", filePath); 

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{ 
    NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"CheckMark" ofType:@"plist"]; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    [fileManager copyItemAtPath:myPathInfo toPath:filePath error:NULL]; 
}  

// load our data from a plist file inside our app bundle 
self.dataArray = [NSMutableArray arrayWithContentsOfFile:filePath]; 
NSLog([[NSString alloc] initWithContentsOfFile:filePath]); 
NSLog(@"%@", filePath); 
NSLog(@"read dataArray"); 

每一件事工作正常,但我看plist文件,沒有什麼變化。 我正在將plist文件寫入我的Documents目錄。

感謝您給我的任何幫助。

+0

@madgnome:恢復了您的更改,因爲除了鏡像我的更改外,您只是重新引入了拼寫錯誤。 – 2010-09-28 13:22:47

+0

@格拉漢李:對不起,我沒有看到你的編輯,當我做我的。 – 2010-09-28 13:25:32

+0

Jim:不要將任意字符串作爲「NSLog」的第一個參數傳遞。您應該傳遞的唯一字符串是格式字符串。如果要傳遞其他字符串,則傳遞僅包含對象格式化程序('%@')的格式字符串,並將要記錄的字符串作爲* second *參數傳遞。另請注意,數組不是字典。如果你正在考慮「關聯數組」,就像PHP中的Perl一樣,你需要NSDictionary。 NSArray嚴格來說是一個串行數組。 – 2010-09-28 16:53:15

回答

0

請記住,您需要使用NSMutableDictionary才能設置值。

+0

而字典不是一個數組,因此嘗試使用NSMutableArray加載字典plist不會給出可靠的(如果可用的話)結果。 – 2010-09-28 16:51:41