Edited at

NSDictionary

More than 3 years have passed since last update.

ありがちな覚え書きです。


未初期化

NSDictionary *dic;

NSLog( @"%@", dic );

(null)


カラ1

NSDictionary *dic = @{};

NSLog( @"%@", dic );

{

}


カラ2

NSDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:5];

NSLog( @"%@", dic );

{

}


アクセス

NSDictionary *dic =

@{
@"string": @"ABCDE",
@"05": @"five",
@-1: @"minus(number)",
@"1": @"one",
@99: @"ninety nine",
@"-1": @"minus(string)",
@"number": @12345,
};
NSLog( @"%@", dic );

{

string = ABCDE;
05 = five;
"-1" = "minus(number)";
1 = one;
99 = "ninety nine";
"-1" = "minus(string)";
number = 12345;
}

上のデータにアクセスします。


直接アクセス

dic[@"number"] // 12345

dic[@"string"] // ABCDE

dic[@-1] // minus(number)
dic[@"-1"] // minus(string)

dic[@"1"] // one
dic[@1] // (null)

dic[@"05"] // five
dic[@"5"] // (null)
dic[@5] // (null)

dic[@99] // ninety nine
dic[@"99"] // (null)


変数でアクセス


int i

i = -1; dic[@(i)] // minus(number)

i = 5; dic[@(i)] // (null)
i = 99; dic[@(i)] // ninety nine


NSNumber *n

n = @-1; dic[n] // minus(number) 

n = @5; dic[n] // (null)
n = @99; dic[n] // ninety nine


NSString *s

s = @"-1"; dic[s] // minus(string)

s = @"05"; dic[s] // five
s = @"5"; dic[s] // (null)
s = @"99"; dic[s] // (null)


NSMutableDictionary

    NSMutableDictionary *mdic = dic.mutableCopy;

mdic[@"number"] = dic[@"string"]; //変更(上書き)
// mdic[@"string"] = nil; //nilは落ちる
// mdic[@"string"] = dic[@"hoge"]; //結果的にnilなので落ちる
// mdic[@"string"] = NULL; //当然NULLも落ちる
mdic[@"05"] = [NSNull null];
[mdic removeObjectForKey:@99]; //削除はこう書くしかない?
NSLog( @"%@", mdic );

{

05 = "<null>";
number = ABCDE;
"-1" = "minus(number)";
1 = one;
"-1" = "minus(string)";
string = ABCDE;
}


キーが存在しない

(mdic[@99] == mdic[@"05"]) = NO  //[NSNull null]と比較

(mdic[@99] == nil) = YES

普通にnilです。


nilなDictionary

NSDictionary *dic; dic[@"hoge"] // nil

((NSDictionary *)nil)[@"hoge"] // nil

落ちません。nilです。