objective-cfor-loopfast-enumeration

Objective-C: Count to every "tenth" in array


I was wondering how do I get sort through an do something different based on every "tenth" item in an array. I don't know much but I think it would kind of go like this...

for (NSDictionary *object in array) {

    if (0==(object % 10)) {

        //DO SOMETHING
    }

}

But this is obviously pseudo code that doesn't work. Can any one help me out with this?


Solution

  • Try this.

    for (NSInteger i = 0 ; i < array.count ; i++)
    {
        if(i%10 == 0)
        {
            // Do Something
        }
    }
    

    or

    for (NSDictionary *object in array)
    {
        NSInteger index = [array indexOfObject:object];
        if(index%10 == 0)
        {
            // Do Something
        }
    }
    

    Added

    Assume that the array is NSArray.

    NSArray *array;
    NSMutableArray *tempArray = [NSMutableArray array];
    for (NSInteger i = 0 ; i < array.count ; i++)
    {
        if(i%10 == 0)
        {
            [tempArray addObject:/*some object*/];
        }
        [tempArray addObject:[array objectAtIndex:i]];
    }
    array = [NSArray arrayWithArray:tempArray];
    

    if array was like below and add A at every 10th.

    |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|....
    // 9 is the first 10th
    // 19 is the second 10th
    

    will be

    |0|1|2|3|4|5|6|7|8|a|9|10|11|12|13|14|15|16|17||18|a|19....
    

    Added

    as rmaddy commented, to insert object, don't need to iterate all objects.

    for (NSInteger i = 0 ; i < array.count ; i+=10)
    

    You can use this. However you can just insert objects at index.

    NSMutableArray *array;  // this is the original array;
    NSArray *objects;       // this is the objects to insert array;
    for(NSInteger i = 0 ; i < objects.count ; i++)
    {
        [array insertObject:objects[i] atIndex:9+(i*11)];
    }