Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C literals for NSSet and NSOrderedSet?

What, if any, NSSet and NSOrderedSet operations can one perform with the new Objective-C collection literals?

For NSArray, NSDictionary, and NSNumber, see here.

FWIW, this Big Nerd Ranch Post says the indexing syntax is supposed to work for NSOrderedSet. But in my tests it does not. And I haven't been able to find anything about creating ordered sets.

like image 405
William Jockusch Avatar asked Aug 13 '12 19:08

William Jockusch


People also ask

What is a literal Objective C?

In Objective-C, any character, numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object initialized with that value. C's type suffixes may be used to control the size of numeric literals.

Is it faster to iterate through an NSArray or an NSSet?

Yes, NSArray is faster than NSSet for simply holding and iterating. As little as 50% faster for constructing and as much as 500% faster for iterating.


1 Answers

There is no Objective-C literal syntax for NSSet. It doesn't really make sense to use index subscripting to access NSSet elements, although key-based subscripting might. Either by wrapping or subclassing, you could add your own.

(Correction): Originally I had thought NSOrderedSet wasn't supported either, but it turns out that using index subscripting is supported, but there doesn't seem to be a way of initializing an NSOrderedSet with the literal syntax. However, you could use initWithArray: and pass a literal array:

NSMutableOrderedSet* oset = [[NSMutableOrderedSet alloc] initWithArray:      @[@"a", @"b", @"c", @"d", @42]];  oset[2] = @3; NSLog(@"OrderedSet: %@", oset); 

Outputs:

OrderedSet: {(     a,     b,     3,     d,     42 )} 

According to this excellent post by Mike Ash, you can add the methods that are used to support indexed subscripting to your own objects.

- (id)objectAtIndexedSubscript:(NSUInteger)index; - (void)setObject: (id)obj atIndexedSubscript: (NSUInteger)index; 

And similar methods for object-based keying:

- (id)objectForKeyedSubscript: (id)key; - (void)setObject: (id)obj forKeyedSubscript: (id)key; 

Thus you could implement a wrapper (or with a bit more work, subclass it) around an NSSet and provide key-based retrieval. Cool!

like image 163
mvl Avatar answered Sep 19 '22 23:09

mvl