Copy object at specific index of mutable array to

2019-09-14 06:28发布

问题:

I have a mutable array that has a range of numbers (that are changed dynamically later on if that helps), I grab a random number's index from that array and want to stick it in another array (also mutable). I'm not sure how to grab the object at a certain index and copy it.

Here's what I tried to do:

[btnRange addObject:@"12"];
[btnRange addObject:@"13"];
[btnRange addObject:@"14"];
[btnRange addObject:@"17"];
[btnRange addObject:@"18"];
[btnRange addObject:@"19"];
//start randomising and adding to btnOrder Array

for (NSInteger i=0; i <= 5; i++) {
     id nxt = btnRange[arc4random_uniform([btnRange count])];
     [btnOrder addObject:(@"%@", nxt];
     //[btnOrder addObject[btnRange(nxt)]; --didn't work
     //[btnOrder addObjectsFromArray:(btnRange. nxt]; --didn't work
     //[btnOrder addObject:nxt]; --didn't work (I'm pretty new to this)
}

How can I take the object at a specific index of the first array and copy it over at the end of the second array?

回答1:

You can get the object from NSMutableArray using [arrayName objectAtIndex:index] 
and add object in NSMutableArray using [arrayName addObejct:object]
[arrayName objectAtIndex:index] return object

[btnRange addObject:@"12"];
            [btnRange addObject:@"13"];
            [btnRange addObject:@"14"];
            [btnRange addObject:@"17"];
            [btnRange addObject:@"18"];
            [btnRange addObject:@"19"];
            //start randomising and adding to btnOrder Array

            for (NSInteger i=0; i <= 5; i++) {
                NSString *nxt = [btnRange objectAtIndex:arc4random()%[btnRange count]];
                [btnOrder addObject:nxt];
            }


回答2:

I'm not sure how to close this, but the suggested thread had the answer I was looking for!

This was my end code if anyone is interested:

[btnRange addObject:@"12"];
[btnRange addObject:@"13"];
[btnRange addObject:@"14"];
[btnRange addObject:@"17"];
[btnRange addObject:@"18"];
[btnRange addObject:@"19"];
//start ordering
for (NSInteger i=0; i <= 5; i++) {
    id nxt = btnRange[arc4random_uniform([btnRange count])];
    btnOrder[i] = nxt;
    [btnRange removeObject:nxt];
}