How to add an object at a random position of a Nsmutablearray?

Asked

Viewed 101 times

2

I am creating an array with the following capacity 15 this way:

meuArray = [[NSMutableArray alloc] initWithCapacity:15];

But when I try to insert an object initially at position 10 in this way:

[meuArray insertObject:algumObjeto atIndex:10];

I get an error saying I oversize the array:

* Terminating app due to uncaught Exception 'Nsrangeexception', Reason: '* -[__Nsarraym insertObject:atIndex:]: index 10 Beyond Bounds for Empty array'

How could I fix this?

1 answer

3


When you initialize the NSMutableArray with a certain capacity, this is used more as a "hint" to the class of how many elements you think of storing (it is the initial number of objects the array can store, but it will expand if necessary). But the array is still empty after the call to alloc / init, reason why you cannot insert an object at position 10.

  • Yes I was seeing this, I saw that the solution would be to fill the array with temporary objects and replace when necessary.... the bad thing is that I need to compose a filter, and in case the stop ta complex. If I could insert it this way, it would be a great help. Because it would help to map the position of the marked options.... But I’m working with the use of a dictionary.

  • 1

    Yeah, obj-c doesn’t have "first-class" support for sparse arrays, like a Javascript-like language. Dictionaries would be the best option in your case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.