Fast Enumeration on an NSArray category for NSIntegers

ios, objective-c

Solution

I doubt that there is a clean way of doing this with NSFastEnumeration, as it heavily depends on the `nextObject` method.

But, you could do it in another way, by adding a block method for it:

@interface NSArray (Integers)
-(void)eachInteger:(void(^)(NSInteger))block;
@end

@implementation NSArray (Integers)
-(void)eachInteger:(void(^)(NSInteger))block {
  for (NSNumber *num in self) {
    block(num.integerValue);
  }
}
@end

That way, you could use it in your code in a similar way:

NSArray *arr = [NSArray arrayWithObjects:[NSNumber numberWithInt:23],
                                         [NSNumber numberWithInt:42],
                                         nil];
...
[arr eachInteger:^(NSInteger i) {
  NSLog(@"The int is %i", i);
}];
// =>
//    The int is 23
//    The int is 42

Perhaps you might want to take a look at the NSArray categories on the Lumumba Framework, which happens to be written by me :D

Problem

Since I use NSInteger arrays frequently, I wrote a category for NSArray (and one for NSMutableArray too) that adds methods such as integerAtIndex:, arrayByAddingInteger:, etc. The methods take care of wrapping/unwrapping the NSInteger in an NSNumber object. What I'm wondering is whether there is a way I can enhance my category so that I can do fast enumeration on the NSIntegers. I would like to be able to write: ``` NSArray* arrayOfIntegers; . . . for(NSInteger nextInteger in arrayOfIntegers) { } ``` ….so that "nextInteger" is pulled out of the NSNumber object behind the scenes. Can I do this?

Original source