68

を使用したいアプリケーションを開発していますNSDictionaryNSDictionaryを使用してデータを保存する方法を完璧な例で説明するサンプルコードを送ってもらえますか?

4

3 に答える 3

191

NSDictionaryNSMutableDictionaryのドキュメントがおそらく最善の策です。彼らは、次のようなさまざまなことを行う方法についてのいくつかの素晴らしい例さえ持っています...

...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] autorelease]

...そしてそれを変更する

[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 objectForKey:@"key"] ではなく dict[@"key"] と入力できます

于 2009-11-19T01:40:31.073 に答える
32
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];
于 2009-11-19T01:39:54.810 に答える
18

主な違い: NSMutableDictionary はその場で変更できますが、NSDictionary は変更できません。これは、Cocoa の他のすべての NSMutable* クラスに当てはまります。NSMutableDictionary は NSDictionary のサブクラスであるため、NSDictionary でできることはすべて両方で行うことができます。ただし、 NSMutableDictionary は、 method など、その場で変更するための補完的なメソッドも追加しますsetObject:forKey:

次のように 2 つの間で変換できます。

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"];
于 2009-11-19T01:41:07.587 に答える