3

Is there any way to manually control which index we want to add our data to with an NSMutableArray? In PHP, for example, we can do:

$foo[2] = "fafa";
$foo[8] = "haha";

Can the manual assigning of indexing be done on NSMutableArray?

4 Answers 4

4

NSMutableArrays are not sparse -- they cannot have gaps where no objects are stored. It is possible to insert an object at any index from 0 to length - 1, using insertObject:atIndex: (as Edu mentioned), but other than that you can only append objects (using addObject:).

If you need to associate objects with arbitrary integers, you can use an NSMapTable -- the functional interface allows integer keys, or simply use an NSMutableDictionary, with NSNumber keys (as drewag suggested).

See also: How to do sparse array in Cocoa

Sign up to request clarification or add additional context in comments.

Comments

2

Just because it's not entirely clear to me that TeamStar wants a sparse array, I'll just mention that you can assign objects to specific indexes within an NSMutableArray – so long as the array is already long enough – using -replaceObjectAtIndex:withObject: and the other -replace… methods.

1 Comment

Well the reason is because the radio button i use is supposed to update the array row[] not add more data into the array in case the users decides to change the option...
2

No that is not possible. I would suggest using an NSMutableDictionary instead. You can use NSNumbers as indexes.

Comments

1
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index

Important Raises an NSRangeException if index is greater than the number of elements in the array.

3 Comments

Raises an NSRangeException if index is greater than the number of elements in the array.
You can use a for loop and fill the array with zeros. But I don't think i'ts a good idea so, have you tried NSMutableDictionary?
but isn't that making it into a function? can i use e.g.; @property (nonatomic, copy) NSMutableArray *rangenans; followed by: [rangenans insertObject:label1.text atIndex:0];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.