标签:
.h文件
#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文件
#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
自定义类实现基于数组/字典Literal Syntax设置和获取数据
标签:
原文地址:http://my.oschina.net/u/734027/blog/424186