I have NSMutableArray
of Results it has 6 items. I want to copy the first three contents
to another NSArray
.
Asked
Active
Viewed 120 times
2
-
1did you tried anything ? – Midhun MP Mar 01 '13 at 04:21
3 Answers
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
-
-
-
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
-
-
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
-
it gives this exception -[NSMutableArray objectAtIndex:]: index 1 beyond bounds for empty array' – Nazia Jan Mar 01 '13 at 04:31
-
-
i have added my more code of array which is with six items in it check that – Nazia Jan Mar 01 '13 at 05:00
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
-
1
-
-
-
Your `firstArray` or the array from where you are fetching data does not contain 6 objects, i would say it contain less than 3!!! Or check before using this code. check for [arry count] – Anoop Vaidya Mar 01 '13 at 05:06
-
-
ObjectData *theCellData = [resultArray objectAtIndex:indexPath.row]; – Nazia Jan Mar 01 '13 at 05:07
-
this is how access items of the arrays like theCellData.category etc – Nazia Jan Mar 01 '13 at 05:08