NSArray, NSDictionary支持下标运算符,使用下标运算符,可以使代码看起来比较优雅,工程师也可以少输入很多字符。那么问题来了,能不能让我们自定义的类也支持下标运算符呢?答案是“可以”,并且实现起来很简单。
如果想支持索引下标,自定义的类需要实现如下两个方法:
- (id)objectAtIndexedSubscript: (NSUInteger)idx;
- (void)setObject: (id)obj atIndexedSubscript: (NSUInteger)idx;
如果想支持键值下标,自定义的类需要实现如下两个方法:
- (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
实现文件
@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