开发者

how to have a list of dictionaries in Objective C?

here is a an example in python

    temy_dict_list = []
my_dict_list.append({'text':'first value', 'value':'number 1'})
my_dict_list.append({'text':'second value', 'value':'number 2'})
my_dict_list.ap开发者_如何转开发pend({'text':'third value', 'value':'number 3'})

I want to implement something the same as this in objective-c !

how can i implement this ? i want a list of dictionaries!


NSMutableArray* list = [NSMutableArray array];
[list addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"first value",@"text", @"number 1",@"value", nil]];
[list addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"second value",@"text", @"number 2",@"value", nil]];
[list addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"third value",@"text", @"number 3",@"value", nil]];


NSArray *array = [NSArray arrayWithObjects:dict1,dict2,nil]


I don't know python (and your code seems wrong to me), but I guess you want to have an array of dictionaries, which is translated to having an NSArray (NSMutableArray in this case) which holds one ore more NSDictionary objects.

You can create an NSMutableArray instance and add add to it some objects.

NSMutableArray *anArray = [[NSMutableArray alloc] init];
[anArray addObject:[NSDictionary dictionaryWithObjectAndKeys: @"first-value", @"text", @"number-1", @"value", nil]];
[anArray addObject:[NSDictionary dictionaryWithObjectAndKeys: @"second-value", @"text", @"number-2", @"value", nil]];
[anArray addObject:[NSDictionary dictionaryWithObjectAndKeys: @"third-value", @"text", @"number-3", @"value", nil]];
// ...
// don't forget to release anArray
[anArray release];

We create an NSDictionary with the class method dictionaryWithObjectAndKeys; we pass a nil-terminated list of values and keys that the dictionary will hold.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜