![](/img/trans.png)
[英]How can I convert an NSDictionary to an NSMutableDictionary?
[英]How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?
我正在開發一個要使用NSDictionary
的應用程序。 任何人都可以給我發送示例代碼來說明如何使用NSDictionary
存儲數據的過程的一個完美示例嗎?
NSDictionary和NSMutableDictionary文檔可能是您最好的選擇。 他們甚至在如何做各種事情上都有很好的例子,例如...
...創建一個NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...重復
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
...使其可變
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
注意:2010年之前的歷史版本:[[dictionary mutableCopy]自動發行]
...並更改它
[mutableDict setObject:@"value3" forKey:@"key3"];
...然后將其存儲到文件中
[mutableDict writeToFile:@"path/to/file" atomically:YES];
...然后再讀一次
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];
...讀取值
NSString *x = [anotherDict objectForKey:@"key1"];
...檢查鑰匙是否存在
if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");
...使用可怕的未來派語法
從2014年開始,您實際上可以鍵入dict [@“ key”]而不是[dict objectForKey:@“ key”]
NSDictionary *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];
[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];
NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);
// now we can save these to a file
NSString *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];
//and restore them
NSMutableDictionary *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];
關鍵區別: NSMutableDictionary可以就地修改,NSDictionary不能 。 可可中的所有其他NSMutable *類都是如此。 NSMutableDictionary是NSDictionary的子類 ,因此您可以對NSDictionary進行的所有操作都可以對兩者進行處理。 但是,NSMutableDictionary還添加了一些補充方法來修改事物,例如setObject:forKey:
方法。
您可以像這樣在兩者之間轉換:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
大概您想通過將數據寫入文件來存儲數據。 NSDictionary有一種方法可以做到這一點(也可以與NSMutableDictionary一起使用):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
要從文件中讀取字典,有一個對應的方法:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
如果要以NSMutableDictionary格式讀取文件,只需使用:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.