Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add data into NSMutableArray by manually assigning index?

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?

like image 547
Joe Shamuraq Avatar asked May 27 '26 18:05

Joe Shamuraq


2 Answers

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

like image 74
jscs Avatar answered May 30 '26 07:05

jscs


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.

like image 23
Ken Thomases Avatar answered May 30 '26 09:05

Ken Thomases



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!