开发者

How to create an NSDictionary that contains an array for every key?

开发者 https://www.devze.com 2023-03-15 20:46 出处:网络
I wanted to know how (if it is possible) to create an NSDictionary that holds an NSArray for ev开发者_如何学编程ery key.

I wanted to know how (if it is possible) to create an NSDictionary that holds an NSArray for ev开发者_如何学编程ery key.

Something like that:

@"FirstKey" - [0], [1], [2], [3]

@"SecondKey" - [0], [1], [2], [3]

@"ThirdKey" - [0], [1], [2], [3]

@"FourthKey" - [0], [1], [2], [3]

Hope you got the idea, thanks ahead!


You can add NSArray instances (or any other collection) as values of an NSDictionary:

NSDictionary *d = [[NSMutableDictionary alloc] init];
[d setValue:[NSArray arrayWithObjects:
               [NSNumber numberWithInteger:0], 
               [NSNumber numberWithInteger:1],
               ...,
               nil]
     forKey:@"FirstKey"];
[d setValue:[NSArray arrayWithObjects:
               [NSNumber numberWithInteger:0], 
               [NSNumber numberWithInteger:1],
               ...,
               nil]
     forKey:@"SecondKey"];
//etc.

Alternatively, if you don't have too many keys/values:

NSArray *values1 = [NSArray arrayWithObjects:
                    [NSNumber numberWithInteger:0], 
                    [NSNumber numberWithInteger:1],
                    ...,
                    nil];
NSArray *values2 = [NSArray arrayWithObjects:
                    [NSNumber numberWithInteger:0], 
                    [NSNumber numberWithInteger:1],
                    ...,
                    nil];
NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
                     values1, @"FirstKey",
                     values2, @"SecondKey",
                     ...,
                     nil];


That's totally possibly. Simplest way is to create your NSArray and then just add that as the object for the key to your NSDictionary

NSArray *myArray = [NSArray arrayWithObjects:@"One",@"Two", nil];
[myDictionary setObject:myArray forKey:@"FirstKey"];


Yes, you can store any object in a dictionary. For numeric values you will need to store them as NSValue or NSNumber objects.

0

精彩评论

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