最近看到Reactcocoa的RACTuple的类,它是一个类似于集合NAarray的类,甚至可以用id value = RACTuple[0]格式来写!我很是纳闷,为什么一个自定义的类可以用这种字面量?或者说 需要什么条件才能让自已写的类能够用这种字面量?
我自已写了一个例子, NSString *a = dog[0]; 会提示报错:expected method to read array element not found on object of type
难道是需要什么协议?
@interface RACTuple : NSObject <NSCoding, NSCopying, NSFastEnumeration>
后来发现还是不行!
最后终于发现了所在:
@interface RACTuple (ObjectSubscripting)
/// Returns the object at that index or nil if the number of objects is less
/// than the index.
- (id)objectAtIndexedSubscript:(NSUInteger)idx;
@end
答案:不必实现任何协议,只需实现这个方法,clang就不会报错!
当然可以参考苹果的clang文档,地址:http://clang.llvm.org/docs/ObjectiveCLiterals.html