0

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

Andrey Chernukha
  • 20,316
  • 16
  • 89
  • 153
hungry
  • 144
  • 8

3 Answers3

1

something like this:

 for (int i = 0; i < arr.count; i++)
{
    [self doSomethingWithArray];

    if (i % 10 == 0)
        [self doSomethingElse];
}
Andrey Chernukha
  • 20,316
  • 16
  • 89
  • 153
1

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.

Prasad
  • 5,365
  • 3
  • 26
  • 35
  • you are right, just the Andrey's answer can be applied to any array immediately without any subclassing. Anyway I thank you for your help. – hungry Aug 30 '14 at 14:21
1

"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
rintaro
  • 48,979
  • 13
  • 123
  • 135