如果你真的喜欢积木,试试这个:
@interface NSArray(blockIteration)
@property (copy, nonatomic, readonly) void (^forEachObject)(void (^block)(NSArray *, id));
@property (copy, nonatomic, readonly) void (^forEachInt)(void (^block)(NSArray *, int));
@property (copy, nonatomic, readonly) void (^forEachDouble)(void (^block)(NSArray *, double));
@end
@implementation NSArray(blockIteration)
-(void (^)(void (^)(NSArray *, id))) forEachObject
{
return [^(void (^block)(NSArray *, id)) {
block = [block copy];
for (id obj in self)
{
block(self, obj);
}
} copy];
}
-(void (^)(void (^)(NSArray *, int))) forEachInt
{
return [^(void (^block)(NSArray *, int)) {
block = [block copy];
for (NSNumber *num in self)
{
block(self, [num intValue]);
}
} copy];
}
-(void (^)(void (^)(NSArray *, double))) forEachDouble
{
return [^(void (^block)(NSArray *, double)) {
block = [block copy];
for (NSNumber *num in self)
{
block(self, [num doubleValue]);
}
} copy];
}
@end
int main()
{
NSArray *array = [NSArray arrayWithObjects:@"Hello", @"World", @"This", @"Is", @"A", @"Test", nil];
array.forEachObject(^(id arr, id obj) {
NSLog(@"%@", obj);
});
}
请注意,此实现依赖于 ARC。