Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to get a subarray from a NSArray?

In Python I can get a subarray easily like this

>> v1 = ['a', 'b', 'c', 'd']
>> v2 = v1[1:]
>> v2
['b', 'c', 'd']

How can I do the equivalent in Objective-C elegantly?

At first I though this method would do the job:

- (void)getObjects:(id[])aBuffer range:(NSRange)aRange

But it copies objects to a buffer location. I will need to add them back to another instance of NSArray. In addition, the compiler complaints about retain/release properties, which I am really not comfortable to deal with.

    id* objs;

    NSRange rng = NSMakeRange(1, [v1 count] - 1);

    [v1 getObjects:objs range:rng]; # Sending '__strong id *' 
                                    # to parameter of type '__unsafe_unretained id *'  
                                    # changes retain/release properties of pointer

So, is there any more elegant way? Or there is no other way but to iterate through objectEnumerator?

like image 756
Anthony Kong Avatar asked Dec 25 '22 12:12

Anthony Kong


1 Answers

NSArray* v1 = @[@"a",@"b",@"c",@"d"];
NSRange rng = NSMakeRange(1,[v1 count]-1);
NSArray* v2 = [v1 subarrayWithRange:rng];
like image 96
Jason Coco Avatar answered Dec 28 '22 10:12

Jason Coco