NSArray, NSDictionary支持下標(biāo)運(yùn)算符,使用下標(biāo)運(yùn)算符,可以使代碼看起來比較優(yōu)雅,工程師也可以少輸入很多字符。那么問題來了,能不能讓我們自定義的類也支持下標(biāo)運(yùn)算符呢?答案是“可以”,并且實(shí)現(xiàn)起來很簡(jiǎn)單。
如果想支持索引下標(biāo),自定義的類需要實(shí)現(xiàn)如下兩個(gè)方法:
- (id)objectAtIndexedSubscript: (NSUInteger)idx;
- (void)setObject: (id)obj atIndexedSubscript: (NSUInteger)idx;
如果想支持鍵值下標(biāo),自定義的類需要實(shí)現(xiàn)如下兩個(gè)方法:
- (id)objectForKeyedSubscript: (id<NSCopying>)key;
- (void)setObject: (id)obj forKeyedSubscript: (id<NSCopying>)key;
例子
頭文件
@interface TestSubscripting : 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
實(shí)現(xiàn)文件
@interface TestSubscripting ()
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) NSMutableDictionary *dictionary;
@end
@implementation TestSubscripting
- (instancetype)init {
self = [super init];
if (self) {
_array = [NSMutableArray array];
_dictionary = [NSMutableDictionary dictionary];
}
return self;
}
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
return self.array[idx];
}
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx {
self.array[idx] = obj;
}
- (id)objectForKeyedSubscript:(id<NSCopying>)key {
return self.dictionary[key];
}
- (void)setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key {
self.dictionary[key] = obj;
}
@end