objective-c subscript

2020-02-18  本文已影响0人  Asteriskjs

参考:https://www.jianshu.com/p/75110e335f37
参考:https://www.jianshu.com/p/68598c0f5aee

现实中

在oc语言世界里,下标语法使用很常见。
例如:

NSDictionary* dict = [[NSDictionary alloc] init];
dict[@"key1"] = @"value1";
NSArray* arr = [[NSArray alloc] init];
arr[0] = @"value1";

问题

那么问题来了,如果让你自定义一个类,实现下标操作呢?

官方的文档已经提供了相应的说明

image.png
image.png

NSDictionary

- (nullable ObjectType)objectForKeyedSubscript:(KeyType)key
- (void)setObject:(nullable ObjectType)obj forKeyedSubscript:(KeyType <NSCopying>)key;
NSArray
- (ObjectType)objectAtIndex:(NSUInteger)index;
- (void)setObject:(ObjectType)obj atIndexedSubscript:(NSUInteger)idx;
自定义类
@interface TestDictionary : NSObject
- (nullable ObjectType)objectForKeyedSubscript:(KeyType)key
- (void)setObject:(RACSignal *)signal forKeyedSubscript:(NSString *)keyPath;
@end
RAC框架
@interface RACSubscriptingAssignmentTrampoline : NSObject

- (nullable instancetype)initWithTarget:(nullable id)target nilValue:(nullable id)nilValue;
- (void)setObject:(RACSignal *)signal forKeyedSubscript:(NSString *)keyPath;

@end
上一篇 下一篇

猜你喜欢

热点阅读