I have an empty mutable array. Is it possible to insert object at index 2 for example, while there’s nothing at index 0 and 1? I mean to increase capacity dynamically or something like that. .Regards.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
NSMutableArrayis not a sparse array; it does not allow empty slots that can be filled in later.initWithCapacity:just hints to the array that it will be filled to a certain amount; it isn’t generally necessary in practice and, unless you know exactly how many items you are going to shove in the array, don’t bother calling it (just useinit).A mutable array will quite efficiently grow in size as objects are added.
If you need a data structure that supports “holes”, then either use something else or put a placeholder object in the slots that are supposed to be empty.
I.e. if you wanted an array with 10 slots, you might do:
You can then check if the retrieved object
isEqual: [NSNull null]to know if the slot is empty or not. And you can usereplaceObjectAtIndex:withObject:to stick an object at a specific index.Or you could use a different data structure; a dictionary with the indices as the keys would work, for example.