Objective-C literals for NSSet and NSOrderedSet?

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!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)