[英]Adding new items to plist programmatically
在最后一個問題中,我要求提供有關從文件保存/加載的建議。 Plist的建議非常棒,但是我當然要遇到某種問題。 我已經用plist填充了TableView> DetailView控制器。 現在,我必須以某種方式保存我的數據(來自parse.com)。 這是我當前的plist,我手動填充了它,為了簡單起見(請不要殺死我),我將所有項目都設為字符串:
<plist version="1.0">
<dict>
<key>orderID</key>
<array>
<string>idKMVX956</string>
<string>idEWUQ321</string>
</array>
<key>orderdate</key>
<array>
<string>28.06.2015</string>
<string>26.06.2015</string>
</array>
<key>match</key>
<array>
<string>Team 3 vs Team 4</string>
<string>Team 1 vs Team 2</string>
</array>
<key>date</key>
<array>
<string>20.06.2015</string>
<string>20.06.2015</string>
</array>
<key>sector</key>
<array>
<string>2</string>
<string>1</string>
</array>
<key>seat</key>
<array>
<string>R2S75</string>
<string>R1S1</string>
</array>
<key>price</key>
<array>
<string>120</string>
<string>60</string>
</array>
</dict>
</plist>
現在我的問題是-如何向此plist添加新訂單。 為了測試,我編寫了以下方法:
- (void)saveToPlist
{
NSString *matchname = @"Team 5 vs Team 6";
NSString *orderHistoryFile = [[NSBundle mainBundle] pathForResource:@"OrderHistory" ofType:@"plist"];
orders = [[NSMutableDictionary alloc] initWithContentsOfFile:orderHistoryFile];
match = [orders objectForKey:@"match"];
NSLog(@"matches: %@", match);
[match addObject:matchname];
NSLog(@"addedTeam; %@", match);
[match writeToFile:orderHistoryFile atomically:YES];
}
但是,盡管第二個NSLog顯示確實將“ Team 5 vs Team 6”行添加到了陣列-plist文件中沒有出現更改,並且沒有出現在tableview中。 為什么?
@Update好吧,我知道我的錯誤在哪里與writetofile在一起。 但是現在執行此方法后-它可以工作一次,我可以看到詳細信息。 然后,我無法再加載數據,並且表格也不會填充。 為什么? Update2所以我不能在我的捆綁包目錄中寫(建議)。 這使我試圖將整個過程轉移到文檔上。 這是我寫的一些代碼:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [[self fileDirectory] stringByAppendingString:@"OrderHistory.plist"];
if (![[NSFileManager defaultManager]fileExistsAtPath:filePath]){
[[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle]pathForResource:@"OrderHistory" ofType:@"plist"] toPath:filePath error:nil];
}
orders = [[NSDictionary alloc] initWithContentsOfFile:filePath];
orderId = [orders objectForKey:@"orderID"];
NSLog(@"count orders: %d", [orderId count]);
}
- (NSString *)fileDirectory{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}
現在我的NSLog計數項目輸出為0。一切都可以在bundle目錄中正常工作,因此我懷疑文件甚至沒有在文檔中創建。 我的錯誤在哪里?
您無法寫入應用程序捆綁包,因此需要將文件保存到Documents
文件夾或等效Documents
夾(例如Caches
文件夾)中。
您的錯誤所在的行中: [[self fileDirectory] stringByAppendingString:@"OrderHistory.plist"];
它應該是-stringByAppendingPathComponent
,當您像字符串一樣附加它時,您會錯過/
,它與directoryPath有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.