1

I am trying to find a structure or way to adding objects from an array to another array. To clarify;

actualArray[] // size not specified
smthArray[1,9,8,4,9]

i want to add objects from smthArray to actualArray from 5th index. Like that,

actualArray[,,,,,1,9,8,4,9]

second times i can add object from begging. Like that,

actualArray[1,9,8,4,9,1,9,8,4,9]

What kind of structure that i need to achieve to this ?

Note: NSSet doesn't fit my purpose because i care about actualArray orders.

Binus
  • 99
  • 1
  • 12

1 Answers1

0

If I understand you correctly, you are trying to use insertObjects:atIndexes: to perform the first step of your description (so the elements begin at index 5). You cannot do this with NSMutableArray because it does not support empty elements. Here is some relevant discussion from the Apple documentation (see https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/index.html#//apple_ref/occ/cl/NSMutableArray):

Note that NSArray objects are not like C arrays. That is, even though you specify a size when you create an array, the specified size is regarded as a “hint”; the actual size of the array is still 0. This means that you cannot insert an object at an index greater than the current count of an array. For example, if an array contains two objects, its size is 2, so you can add objects at indices 0, 1, or 2. Index 3 is illegal and out of bounds; if you try to add an object at index 3 (when the size of the array is 2), NSMutableArray raises an exception.

If you want to achieve what you describe you need to first fill the space with NSNull objects:

for (NSUInteger i = 0; i < tempArray.count; i++) {
    [actualArray addObject:[NSNull null]];
}

Then you can add your tempArray content:

[actualArray addObjectsFromArray:tempArray];

Finally you can replace the nulls with content:

[actualArray replaceObjectsInRange:NSMakeRange(0, tempArray.count) withObjectsFromArray:tempArray.count];
Mike Woods
  • 76
  • 3
  • I've done your way but it wasn't useful for my case. And also i don't want to write for loop like that. :) I just look for alternatives... (like NSSet, etc ) Are there any other structure can do what i want ? – Binus Apr 21 '16 at 17:22
  • The purpose of the loop is to avoid knowing how many elements you are trying to reserve. You could just assign 5 `NSNull`s but that would be fragile. However, if the solution doesn't meet your need perhaps you can edit your question to more clearly explain what you are attempting to achieve. – Mike Woods Apr 21 '16 at 20:31