Chapter 1 Adding Object and Index Subscription support
Similar to the dictionary and array that use subscript to access.
@interface Person : NSObject@property (nonatomic, copy) NSString *firstName;@property (nonatomic, copy) NSString *lastName;// object subscription- (id) objectForKeyedSubscript:(id )paramKey; - (void) setObject:(id)paramObject forKeyedSubscript:(id )paramKey; // index subscription - (id) objectAtIndexedSubscript:(NSUInteger)paramIndex; - (void) setObject:(id)paramObject atIndexedSubscript:(NSUInteger)paramIndex; @end
NSString *const Kfirstnamekey = @ "FirstName"; NSString *const Klastnamekey = @ "LastName"; @implementation person-(ID) Objectforkeyedsubscript: (ID) paramkey{NS Object *keyasobject = (NSObject *) Paramkey; if ([Keyasobject iskindofclass:[nsstring class]]) {NSString *keyasstring = (NSString *) keyasobject; if ([Keyasstring isEq Ualtostring:kfirstnamekey] | | [Keyasstring Isequaltostring:klastnamekey]) {return [self valueforkey:keyasstring];} } return nil; }-(void) SetObject: (ID) paramobject forkeyedsubscript: (ID) paramkey{nsobject *keyasobject = (N SObject *) Paramkey; if ([Keyasobject iskindofclass:[nsstring class]]) {NSString *keyasstring = (NSString *) keyasobject; if ([Keyasstring isEq Ualtostring:kfirstnamekey] | | [Keyasstring Isequaltostring:klastnamekey]) {[Self setValue:paramObjectforKey:keyAsString];} }}-(ID) Objectatindexedsubscript: (nsuinteger) paramindex{switch (paramindex) {case 0:{return self.firstname; BreaK } Case 1:{return self.lastname, Break,} default:{[NSException raise:@ "Invalid index" Format:nil];}} return nil; }-(void) SetObject: (ID) paramobject atindexedsubscript: (nsuinteger) paramindex{switch (paramindex) {case 0:{ Self.firstname = Paramobject; Break } case 1:{self.lastname = Paramobject; break;} default:{[NSException raise:@ "Invalid index" Format:nil];}} } @end
Use subscripts to manipulate objects.
Person *person = [Person new];person[kFirstNameKey] = @“Tim”;person[kLastNameKey] = @“Cook”;NSString *firstNameByKey = person[kFirstNameKey];NSString *lastNameByKey = person[kLastNameKey];NSString *firstNameByIndex = person[0];NSString *lastNameByIndex = person[1];if ([firstNameByKey isEqualToString:firstNameByIndex] && [lastNameByKey isEqualToString:lastNameByIndex]){ NSLog(@“Success”);} else { NSLog(@“Something is not right”);}
IOS7 Programming Cookbook Notes