2

I have NSMutableArray of Results it has 6 items. I want to copy the first three contents to another NSArray.

rptwsthi
  • 10,094
  • 10
  • 68
  • 109
Nazia Jan
  • 783
  • 3
  • 13
  • 19

3 Answers3

5

Just use subarrayWithRange::

NSMutableArray *oldArray = ... // the mutable array with the 6 objects
NSArray *result = [oldArray subarrayWithRange:NSMakeRange(0, MIN(3, oldArray.count))];
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • wow nice one... never thought of this :) – Anoop Vaidya Mar 01 '13 at 04:46
  • it is giving exception – Nazia Jan Mar 01 '13 at 05:03
  • Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 1 beyond bounds for empty array' – Nazia Jan Mar 01 '13 at 05:03
  • Did you include the same check I have using `MIN(3, oldArray.count)`? This ensures the code will work even if `oldArray` has less than 3 objects in it. The error indicates that your array is empty. – rmaddy Mar 01 '13 at 05:13
  • and if i want array items from 3 to 6 then how can i write please – Nazia Jan Mar 01 '13 at 06:16
  • Just update the values you pass to `NSMakeRange`. But you may need to do more validation of the array count. If you want objects 3 to 6 then make sure the array has at least 6 objects in it first. Just remember that the second argument to `NSMakeRange` is the length, not the end index. – rmaddy Mar 01 '13 at 06:25
2
NSMutalbeArray *newArray=[[NSMutableArray alloc] init];
for(int i=0; i < results.count; i++){
    [newArray addObject:results[i]];
    if(i == 2)
       break;
}
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
2

Try this simple loop:

NSMutableArray *resultantArray=[NSMutableArray new];
for(NSInteger i=0;i<3;i++){
    [resultantArray addObject:firstArray[i]];
}
Scott Berrevoets
  • 16,921
  • 6
  • 59
  • 80
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140