NSDictionaryの覚え書き

Last-modified: 2014-01-10 (金) 18:39:45

NSDictionary

初期化

リテラル記法

NSDictionary *aDict = @{
	@"firstName" : 	@"naoki",
	@"lastName" : 	@"Taisawa",
	@"address" : 	@"Tokyo",
	@"zip" : 		@"123-4567",
	@"phone" : 	@"090-1234-5678",
	@"birthday" : 	@"2014-01-01",
	@"email" : 	@"abc@example.com",
	@"alias" : 	@"abc@example.com",
};

1つのエントのみで初期化

//dictionaryWithObject
NSDictionary *bDict = [NSDictionary dictionaryWithObject:@"Human" forKey:@"race"];

キー配列とオブジェクト配列をペアにして

// dictionaryWithObjects:forKeys:
NSDictionary *cDict = [NSDictionary
	dictionaryWithObjects:@[@"blue",    @"rabit",   [NSNumber numberWithInt:7]]
	forKeys:@[@"color",   @"pet",     @"lucky"]
];

同上だが、count:で指定された数だけ

static const NSInteger N_ENTRIES = 26;
NSString *keyArray[N_ENTRIES];
NSNumber *valueArray[N_ENTRIES];
NSInteger i = 0;
for (i = 0; i < N_ENTRIES; i++ ) {
	char charValue = 'a' + i;
	keyArray[i] = [NSString stringWithFormat:@"%c", charValue];
	valueArray[i] = [NSNumber numberWithChar:charValue];
}
dDict = [NSDictionary
	dictionaryWithObjects:(id *)valueArray
	forKeys:(id *)keyArray count:N_ENTRIES];
}

キーとオブジェクトが交互に現れる配列から

NSDictionary *eDict = [NSDictionary dictionaryWithObjectsAndKeys:
	@"拾",
	@(10),
	@"九",
	@(9),
	@"八",
	@(8),
	@"You are lucky!",
	@(7),
	@"六",
	@(6),
	@"五",
	@(5),
	@"四",
	@(4),
	nil];

既存の辞書をコピーして

aDict = [NSDictionary dictionaryWithDictionary:bDict];
// NSMutableDictionary で使う。

操作

NSUInteger aCount, bCount;
aCount = [aDict count];
bCount = bDict.count;
NSLog(@"エントリ数を返す\n辞書a -> %lu\n辞書b -> %lu", aCount, bCount);

キーにマッチするオブジェクトを取得。

id anObject;
id aKey = @(7);
anObject = [eDict objectForKey:aKey];
NSLog(@": key: %@, value: %@", [aKey description], [anObject description]);

引数と同じオブジェクトを持つ、すべてのキー値を配列で返す。

id anObject;
NSArray *anArray;
anObject = (id)(NSString *)@"abc@example.com";
anArray = [aDict allKeysForObject:anObject];
for (id obj in anArray) {
	NSLog(@"  object: %@", [obj description]);
}

比較

辞書の完全一致"

BOOL isEqual = NO;
isEqual = [aDict isEqualToDictionary:fDict];
NSLog(@"  are equal?  %@", isEqual ? @"Yes!" : @"No..." );

ファイル入出力

自己記述

NSString *aString;
aString = [cDict description];
NSLog(@"自己記述 description\n%@", aString);
}

プロパティ形式でファイルへ書込

BOOL isSuccess = NO;
isSuccess = [aDict writeToFile:aPathString atomically:YES];
NSLog(@"  Is writing successfully? %@", isSuccess ? @"YES!" : @"No...");

プロパティ形式のファイルから読み込んで初期化

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:aPathString];
NSLog(@" load from file .plist.\n%@", dict);

NSMutableDictionary

初期化

空の辞書を作成

NSMutableDictionary *aMutaDict = [NSMutableDictionary dictionary];

容量を指定(あくまでも指標であって、したがう必要は無い)

NSMutableDictionary *bMutaDict = [[NSMutableDictionary alloc] initWithCapacity:10];

既存の辞書をコピーして

NSDictionary aDict = [NSDictionary dictionaryWithDictionary:otherDicti];

リテラル記法

NSMutableDictionary *dMutaDict = @{
	@"firstName" : [NSNull null],
	@"lastName" : @"Taisawa",
	@"address" : @"Tokyo",
	@"zip" : @"123-4567",
	@"phone" : @"090-1234-5678",
	@"birthday" : @"2014-01-01",
	@"email" : @"abc@example.com",
	@"alias" : @"abc@example.com",
}.mutableCopy;

オブジェクトとキー値が交互にならんだリテラルから

NSMutableDictionary *cMutaDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
	@"拾",
	@(10),
	@"九",
	@(9),
	@"八",
	@(8),
	@"You are lucky!",
	@(7),
	nil];

エントリの追加と削除

追加(上書き)

aMutaDict[@"tel"] = @"03-5678-1234";
NSString *aKey = @"firstName";
NSString *anObject = @"naoki";
[aMutaDict setObject:anObject forKey:aKey];

上書きは追加と同じ。上書きして欲しくないなら、エントリが存在するかどうかのコードで挟む。

ほかの辞書の内容を追加

[aMutaDict addEntriesFromDictionary:otherDict];

ほかの辞書で、全て置き換え

[aMutaDict setDictionary:otherDict];

キーに対応するエントリを削除

[aMutaDict removeObjectForKey:aKey];

配列に含まれる複数のキーへ対応しているエントリをすべて削除

NSArray *keys = @[@"address", @"zip", @"phone"];
[aMutaDict removeObjectsForKeys:keys];

すべてのエントリを削除

[aMutaDict removeAllObjects];

列挙

キーを使った高速列挙

for (id anObj in aMutaDict) {
	id value = aMutaDict[anObj];
	NSLog(@"key: %@  =>  value: %@", [key description], [value description] );
}

「オブジェクトで使ってキーをソート」して、高速列挙。上の逆。

NSArray *sortedKeys = [aDict keysSortedByValueUsingSelector:@selector(compare:)];
for (NSString *key in sortedKeys) {
	id value = aDict[key];
	NSLog(@" key: %@\t\t  =>  value: %@", key, value);
}

各キーへ任意順でアクセスする列挙子

id aKey;
NSEnumerator *anEnumerator;
anEnumerator = [aDict keyEnumerator];
while ((aKey = [anEnumerator nextObject]) != nil) {
	NSLog(@"  a key: %@", [aKey description]);
}

値オブジェクトへ任意順でアクセスする列挙子を返す。

id anObject;
NSEnumerator *anEnumerator;
anEnumerator = [fDict objectEnumerator];
while ( (anObject = [anEnumerator nextObject]) != nil ) { /* */}

全要素をブロックで評価

[aDict enumerateKeysAndObjectsUsingBlock:
	^(id key, id value, BOOL *stop) {
		NSLog(@" key: %@\t\t  =>  value: %@", [key description], [value description]);
	}
];