.h文件
#import@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文件
#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
使用
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