Rogare
Rogare

Reputation: 3274

Setting up a NSDictonary with NSSet objects

Is there a way to setup a NSSDictionary with NSSet objects in one command? Or, do objects need to be created for all of the sets first?

For example, is something like this possible?

NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:{@"orange",@"lemon"},@"citrus",{@"horse",@"moose",@"goose"},@"animals",nil];

Thanks for reading.

Upvotes: 1

Views: 1516

Answers (2)

mackross
mackross

Reputation: 2234

There is no NSSet literal in Objective-C only NSArray literals.

NSDictionary *dictionary = @{ @"citrus" : @[ @"orange", @"lemon" ], @"animals" : @[ @"horse", @"moose" ,@"goose" ] };

So the above will give you a NSDictionary with an NSArray containing orange and lemon for the key citrus and an NSArray containing horse, moose, and goose for the key animals.

You could access those NSArrays like so dictionary[@"animals"] and dictionary[@"citrus"]

You can nest those literal accessors as well so dictionary[@"animals"][0] would give you horse.

or even use array methods

[dictionary[@"citrus"] count] would give you 2

Upvotes: 1

Wade Tregaskis
Wade Tregaskis

Reputation: 2018

There is no NSSet literal, no. But you can use an NSArray literal to initialise an NSSet… it's about the shortest you can get:

NSDictionary *dictionary = @{
    @"citrus":  [NSSet setWithArray:@[@"orange", @"lemon"]],
    @"animals": [NSSet setWithArray:@[@"horse", @"moose", @"goose"]]};

Upvotes: 3

Related Questions