如果您确实想绑定到特定的数组索引,您可以创建一个包装器对象。像这样的东西。它可以让你绑定到item0
,item1
等等。没有范围检查,如果您更改数组的大小,它会中断,但您明白了。
界面
@interface MyArrayBinder : NSObject {
NSMutableArray *array;
}
- (id)initWithMutableArray:(NSMutableArray *)theArray;
- (NSMutableArray *)array;
@end
执行
#include <objc/runtime.h>
static NSInteger _indexFromSelector(SEL sel) {
return [[NSStringFromSelector(sel) stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]] integerValue];
}
static void _dynamicSetItem(MyArrayBinder *self, SEL sel, id obj) {
[self.array replaceObjectAtIndex:_indexFromSelector(sel) withObject:obj];
}
static id _dynamicItem(MyArrayBinder *self, SEL sel) {
return [self.array objectAtIndex:_indexFromSelector(sel)];
}
@implementation MyArrayBinder
- (id)initWithMutableArray:(NSMutableArray *)theArray {
self=[super init];
if (self) {
array=theArray;
for(NSUInteger i=0; i<[array count]; i++) {
class_addMethod([self class], NSSelectorFromString([NSString stringWithFormat:@"item%lu", i]), (IMP) _dynamicItem, "@@:");
class_addMethod([self class], NSSelectorFromString([NSString stringWithFormat:@"setItem%lu:", i]), (IMP) _dynamicSetItem, "v@:@");
}
}
return self;
}
- (NSMutableArray *)array {
return array;
}
@end