2011年5月13日金曜日

NSDictionaryの使い方--Objective-C--

int main (int argc, const char * argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    //NSDictionaryを作成
    //値、キー,値、キー,・・・・・の順で指定していく
    NSDictionary *dict1 =[NSDictionary dictionaryWithObjectsAndKeys:
                          @"John",@"name",
                          [NSNumber numberWithInt:8],@"age",
                          @"blue",@"color"
                          ,nil];
    NSLog(@"%@",dict1);// age = 8 color = blue name =Jhon
    
    //値とキーをそれぞれ配列で指定して作成する
    NSArray *keys =[NSArray arrayWithObjects:@"name",@"age",@"color", nil];
    NSArray *vals =[NSArray arrayWithObjects:@"Paul",@"7",@"brown", nil];
    NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:vals forKeys:keys];
    NSLog(@"%@",dict2);// age = 7 color = brown name =Paul

    //キーを指定して要素を取得
    id obj1 =[dict1 objectForKey:@"name"];
    NSLog(@"%@",obj1);//John
    
    //値とキーをそれぞれ配列として取得
    NSArray *kArr =[dict1 allKeys];
    NSArray *vArr =[dict1 allValues];
    NSLog(@"%@and%@",kArr,vArr);//(name,age,color) and (John,8,blue)
    
    //辞書の要素数を取得
    NSUInteger dictCount =[dict1 count];
    NSLog(@"%d",dictCount);//3
    
    //辞書の比較
    BOOL isDictEquals =[dict1 isEqualToDictionary:dict2];
    NSLog(@"%d",isDictEquals);//0(False)
    
    [pool drain];
    return 0;
}

0 件のコメント:

コメントを投稿