Search code examples
iosarraysswiftuitableviewnsrange

NSRange array of odd or even count


I have an array of 977 of data, I've been trying to split it to 20 section in UITableView but i cannot get it correct, i am trying to do it dynamically. like if i got an array of 312 or 32 or 545 the equation should divide it, and add the last odd elements in array, I'm placing the new data in array of arrays.

So here is what I'm doing :

var dataof977 = Mydata()
var mutA  = NSMutableArray()

        for (var i = 0; i < 19; i++)
        {
            var halfArray : NSArray!
            var theRange = NSRange()

            theRange.location = i*19;
            theRange.length = dataof977.afa.count / 19
            halfArray = dataof977.afa.subarrayWithRange(theRange)
            mutA.addObject(halfArray)
        }

Note : dataof977 is reference of class and afa is a String array.

What am i missing here ?s


Solution

  • Three things:

    1. You need to start each location where the previous left off. To do this, introduce a location variable to keep track of where you are in the original array.
    2. Some of your sections will need more items since your count might not be a multiple of 20. I think your best best is to give the first n sections an extra item to make up for the leftovers.
    3. Your loop needs to iterate 20 times, not 19. I have changed it to use for in which is better Swift style.

    var mutA  = NSMutableArray()
    
    let sublength = dataof977.afa.count / 20
    let leftovers = dataof977.afa.count % 20
    
    // location of each new subarray    
    var location = 0
    
    for i in 0..<20
    {
        var length = sublength
    
        // The first sections will have 1 more each
        if i < leftovers {
            length++
        }
    
        let theRange = NSMakeRange(location, length)
    
        let halfArray = dataof977.afa.subarrayWithRange(theRange)
        mutA.addObject(halfArray)
    
        // move location up past the items we just added
        location += length
    }