Skip to content

Instantly share code, notes, and snippets.

@robbdimitrov
Created June 19, 2013 09:21
Show Gist options
  • Save robbdimitrov/5812953 to your computer and use it in GitHub Desktop.
Save robbdimitrov/5812953 to your computer and use it in GitHub Desktop.
Test object subscripting in Objective-C
//
// main.m
// SubscriptingSample
//
// Created by Robert Dimitrov on 6/19/13.
// Copyright (c) 2013 Robert Dimitrov. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Person.h"
#import "PersonHolder.h"
int main(int argc, char *argv[]) {
@autoreleasepool {
Person *john = [[Person alloc] init];
[john setFullName:@"John Appleseed"];
Person *max = [[Person alloc] init];
[max setFullName:@"Mad Max"];
PersonHolder *personHoder = [[PersonHolder alloc] init];
personHoder[0] = john;
personHoder[@"Max"] = max;
NSLog(@"%@", [personHoder[0] fullName]);
NSLog(@"%@", [personHoder[@"Max"] fullName]);
}
}
//
// Person.h
// SubscriptingSample
//
// Created by Robert Dimitrov on 6/19/13.
// Copyright (c) 2013 Robert Dimitrov. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (copy) NSString *fullName;
@end
//
// Person.m
// SubscriptingSample
//
// Created by Robert Dimitrov on 6/19/13.
// Copyright (c) 2013 Robert Dimitrov. All rights reserved.
//
#import "Person.h"
@implementation Person
@end
//
// PersonHolder.h
// SubscriptingSample
//
// Created by Robert Dimitrov on 6/19/13.
// Copyright (c) 2013 Robert Dimitrov. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface PersonHolder : NSObject
- (id)objectAtIndexedSubscript:(NSUInteger)idx;
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
- (id)objectForKeyedSubscript:(id <NSCopying>)key;
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;
@end
//
// PersonHolder.m
// SubscriptingSample
//
// Created by Robert Dimitrov on 6/19/13.
// Copyright (c) 2013 Robert Dimitrov. All rights reserved.
//
#import "PersonHolder.h"
@interface PersonHolder ()
@property (copy) NSMutableArray *peopleArray;
@property (copy) NSMutableDictionary *peopleDictionary;
@end
@implementation PersonHolder
- (id)init {
self = [super init];
if (self) {
_peopleArray = [[NSMutableArray alloc] init];
_peopleDictionary = [[NSMutableDictionary alloc] init];
}
return self;
}
#pragma mark - Subscripting
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
return [self peopleArray][idx];
}
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx {
[self peopleArray][idx] = obj;
}
- (id)objectForKeyedSubscript:(id <NSCopying>)key {
return [self peopleDictionary][key];
}
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key {
[self peopleDictionary][key] = obj;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment