2014-01-05 64 views
0

在執行其他操作之前,如何等待plist寫操作完成?如何等待plist寫操作完成?

// Write plist file 
NSString *pathToPlist = [NSString pathWithComponents:@[[Util documentsDirectoryPath], @"Settings.plist"]]; 
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:pathToDocumentsPlist]; 
[dic setObject:@"SomeObject" @"SomeKey"]; 
[dic writeToFile:pathToDocumentsPlist atomically:YES]; 

// Read plist file 
NSDictionary *updatedDictionary = [NSDictionary dictionaryWithContentsOfFile: pathToPlist]; 

在這種情況下,我想updatedDictionary有更新的plist的值,然而,plist中寫入方法(writeToFile)似乎是異步的,並且需要的時間量來完成。因此,updatedDictionary傾向於讀取舊的而不是更新的配置,因爲在讀取plist時,保存操作未完成。

如何解決此問題?只是一個純粹的猜測,可以設置atomically:NO可能有幫助嗎?謝謝!

+5

'將writeToFile:原子:'是同步的,該方法返回時結束。您發佈的代碼是從您寫入的不同路徑讀取的。 – rmaddy

+0

'pathToPlist'和'pathToDocumentsPlist'似乎都指向相同的路徑,儘管它們是2個'NSString'對象,但這個問題可以解決嗎? – lwxted

+1

'pathToDocumentsPlist'是較早創建的'NSString','pathToPlist'稍後單獨創建。如果'writeToFile:atomically:'是同步的,我會試着找出自己出了什麼問題。謝謝:) – lwxted

回答

0

第一點這個方法是不是異步的,它是同步的,當操作成功與否它返回一個布爾值,所以你可能不檢查是否保存,而且很可能這是你的問題。檢查writeToFile的返回值:原子地:!

現在,一個非常簡單的問題,爲什麼你這樣做?

這是你的代碼:

// Write plist file 
NSString *pathToPlist = [NSString pathWithComponents:@[[Util documentsDirectoryPath], @"Settings.plist"]]; 
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:pathToDocumentsPlist]; 
[dic setObject:@"SomeObject" @"SomeKey"]; 
[dic writeToFile:pathToDocumentsPlist atomically:YES]; 

// Read plist file 
NSDictionary *updatedDictionary = [NSDictionary dictionaryWithContentsOfFile: pathToPlist]; 

首先,你正在閱讀的plist中的字典 - OK

其次要更新在字典中的數據 - OK

三要保存字典到plist再次 - 好吧

第四你再次得到plist - 爲什麼?

你的字典裏已經有了plist的內容,當你使用「dic」更新plist的時候,爲什麼你需要再次閱讀它,如果它的plist內容完全相同的話?在你的代碼中,dic和plist是相同的。

如果你想確保內容被保存,該方法將writeToFile:原子返回boolean在這裏你可以看到,如果操作成功與否。順便說一下,如果這個方法返回一個布爾值,表示操作已經完成,那麼該方法不能是異步的,要是異步的,它應該使用塊而不是返回值。

關於你的問題與「原子」,不,它不會使它同步或異步,以最簡單的方式描述它,這原子意味着「沒有人」可以訪問此文件的內容,直到它完全保存的,所以它會在某些地方暫時保存,當它完成,它會移動到最終目的地,因此,如果某個對象嘗試讀取/更新/刪除它完全保存它之前,是不可能的。

末試試這個寫你的plist:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 

if([dic writeToFile:[documentsDirectory stringByAppendingString:@"/Settings.plist"] atomically:YES]) 
//it worked 

歡呼聲,

羅伯託

+0

謝謝,我已經解決了這個問題。爲了回答這個問題,我使用另一個'dictionaryWithContentsOfFile'來獲取內容的原因是,字典也在別處修改(在另一個線程中)。無論如何感謝您的回答! – lwxted