Jordy Groote Jordy Groote - 5 months ago 15
iOS Question

Insert object to nsmutable array at index dynamicly is not working

I'm trying to add a

URL
to every fifth row of the array, but for some weird reason this is not working.

This works, and I want to make this dynamically.

self.tableData.insertObject(url!, atIndex: 0);
self.tableData.insertObject(url!, atIndex: 5);
self.tableData.insertObject(url!, atIndex: 10);
self.tableData.insertObject(url!, atIndex: 15);
self.tableData.insertObject(url!, atIndex: 20);
self.tableData.insertObject(url!, atIndex: 25);


The array:

var tableData:NSMutableArray = NSMutableArray()


The loop I tried and in my eyes should work.

for(var i = 0; i < (tableData.count + 3); i += 1) {
if(i % 5 == 0){
dispatch_async(dispatch_get_main_queue())
{
self.tableData.insertObject(url!, atIndex: i);
}
}

}


The error:


'NSRangeException', reason: '-[__NSCFArray insertObject:atIndex:]: index (26) beyond bounds (24)'

Answer

As @patrick and @chronikum say, your index, or i runs "over the edge"

Your problem lies here:

for(var i = 0; i < (tableData.count + 3); i += 1)

If you have 24 elements in your tableData then you actually loop over 3 elements that are not there. That would work if you don't actually do anything in your loop.

But when you say:

self.tableData.insertObject(url!, atIndex: i);

and i is larger than tableData.count, then you are trying to insert something into tableData at a position that isn't there (26 in this case, in an array that holds 24 elements).

I don't know if this does what you'd like, but a simple fix would be to just run to the end of tableData, so you could change your for loop to:

for(var i = 0; i < (tableData.count); i += 1)

And if you'd like to do this more "Swifty" then maybe you could look at the enumerate function as described in The Swift Programming Guide (search for "Iterating Over an Array")

Hope that helps.

Comments