Reputation: 174
Using Objective-C, is it possible to go through an array by groups : exemple :
NSArray *arr = 1, 2, 3, ....100;
Every 10 objects, do something and go on
so :
object 0 to 9 : you do something with each object and after the 10° object you do a last action
then object 10 to 19 : you do something with each object and after the 19° object you do a last action
and so on until the last object
thank you for your help
Upvotes: 0
Views: 120
Reputation: 51911
"enumerating by group"; If you want exactly as stated, you can subclass NSEnumerator
.
For example:
In your Application code:
#import "NSArray+SubarrayEnumerator.h"
NSArray *arr = ...;
for(NSArray *grp in [arr subarrayEnumeratorEach:10]) {
// do what you want.
}
NSArray+SubarrayEnumerator.h
#import <Foundation/Foundation.h>
@interface NSArray (SubarrayEnumerator)
- (NSEnumerator *)subarrayEnumeratorEach:(NSUInteger)perPage;
@end
NSArray+SubarrayEnumerator.m
#import "NSArray+SubarrayEnumerator.h"
@interface _NSArraySubarrayEnumeratorEach : NSEnumerator
@property (assign, nonatomic) NSUInteger cursor;
@property (assign, nonatomic) NSUInteger perPage;
@property (strong, nonatomic) NSArray *src;
@end
@implementation NSArray (SubarrayEnumerator)
- (NSEnumerator *)subarrayEnumeratorEach:(NSUInteger)perPage {
_NSArraySubarrayEnumeratorEach *enumerator = [[_NSArraySubarrayEnumeratorEach alloc] init];
enumerator.perPage = perPage;
enumerator.src = self;
return enumerator;
}
@end
@implementation _NSArraySubarrayEnumeratorEach
- (id)nextObject {
NSUInteger start = _cursor;
if(start >= _src.count) {
return nil;
}
NSUInteger count = MIN(_perPage, _src.count - start);
_cursor += _perPage;
return [_src subarrayWithRange:NSMakeRange(start, count)];
}
@end
Upvotes: 1
Reputation: 6034
No it is not possible in Objective-C with in-built functions which matches your exact description. There are crude ways to do it by loops which matches your exact description.
But if you are aware before hand that you are going to make such type of operations, define your own data-structure. Create an NSObject
sub-class, define your items (10 items which you were talking about) in it. Then in array, you can directly take out each instance of it comprising of your defined NSObject
.
Upvotes: 1
Reputation: 21808
something like this:
for (int i = 0; i < arr.count; i++)
{
[self doSomethingWithArray];
if (i % 10 == 0)
[self doSomethingElse];
}
Upvotes: 1