开发者

Array of pointers in Objective-C using NSArray

I am writting program for my iphone and have a qestion.

lets say i have class named my_obj

class my_obj  
{  
  NSString  *name;  
  NSinteger  *id;  
  NSinteger  *foo;  
  NSString   *boo;  
}  

now i allocate 100 objects from type my_obj and insert them to array from type NSArray.

then i want to sort the Array in two different ways. one by the name and the second by

the id.

i want to allocate another two arrays from type NSArray

*arraySortByName     
*arraySortById  

what i need to do if i just want the sorted arrays to be referenced to the original array

so i will get two sorted arrays that point to the original array (that didnt changed!)

i other word i dont want t开发者_如何转开发o allocate another 100 objects to each sorted array.


You can use the NSArray method sortedArrayUsingFunction:context: (or the other NSArray sort functions) which returns a new array.

From the documentation:

The new array contains references to the receiver’s elements, not copies of them.


If you mean that the sorted arrays should just be pointers to the original array, how is this supposed to work? The order of the elements in the sorted arrays is different.

Or I didn't get your question.


This is really easy. Check it:

NSSortDescriptor * sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSSortDescriptor * sortByID = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];

NSArray * sortedByName = [original sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortByName]];
NSArray * sortedByID = [original sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortByID]];

This will not create copies of your objects. So you will still have only 100 allocated my_obj objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜