. h file
#import <Foundation/Foundation.h> @interface testkvc:nsobject {nsmutabledictionary *mdictionary; Nsmutablearray *marray;} -(void) SetObject: (ID) object forkeyedsubscript: (ID < nscopying >) akey;-(ID) Objectforkeyedsubscript: (ID) key;-( void) SetObject: (ID) anobject atindexedsubscript: (Nsuinteger) index;-(ID) objectatindexedsubscript: (NSUInteger) idx; @end
. m file
#import "TestKVC.h" @implementation TestKVC- (ID) init { self = [super init]; if (self) { mArray = [NSMutableArray array]; mdictionary = [nsmutabledictionary dictionary]; } return self;} - (void) SetObject: (ID) Anobject atindexedsubscript: (Nsuinteger) index { [ Marray insertobject:anobject atindex:index];} - (ID) objectatindexedsubscript: (Nsuinteger) idx { return [marray OBJECTATINDEX:IDX];} - (void) SetObject: (ID) Object forkeyedsubscript: (id < nscopying >) aKey { [mdictionary setobject:object forkey:akey];} - (ID) objectforkeyedsUbscript: (ID) key { return [mdictionary objectforkey:key];} @end
Use
TestKVC *test = [[TestKVC alloc] init]; test[@ "Key"] = @ "Hello"; id value = test[@ "key"]; [test setobject:@ "World" forkeyedsubscript:@ "Key0"]; id value0 = [test objectforkeyedsubscript:@ "Key0"]; nslog (@ "%@ %@", value, value0); // hello world test[0] = @ "Hello"; test[1] = @ "World"; id v0 = test[0]; id v1 = test[1]; nslog (@ "%@ %@", v0, v1); // hello woRld
Custom class implementations set and get data based on array/dictionary literal syntax