2013-05-28 52 views
0

我有一個類officeSupply如何排序自定義NSArray?

@interface OfficeSupply : NSObject 

@property (nonatomic, strong) NSString *itemName; 
@property (nonatomic) int total; 
@property (nonatomic) int price; 
@property (nonatomic) int quantity; 
@property (nonatomic, strong) UITextField *quantityText; 
@property (nonatomic, strong) UIImage *itemPic; 

-(id)initWithName:(NSString *)itemName total:(int)total price:(int)price quantity:(int)quantity picture:(UIImage *)itemPic; 

@end 

在我看來,我有

OfficeSupply *item1 = [[OfficeSupply alloc] initWithName:@"Stapler" total:0 price:50 quantity:0 picture:[UIImage imageNamed:@"stapler.jpg"]]; 
OfficeSupply *item2 = [[OfficeSupply alloc] initWithName:@"Paper" total:0 price:150 quantity:0 picture:[UIImage imageNamed:@"101291.jpg"]]; 
OfficeSupply *item3 = [[OfficeSupply alloc] initWithName:@"Pen" total:0 price:45 quantity:0 picture:[UIImage imageNamed:@"pen.jpg"]]; 
_items =[NSArray arrayWithObjects:item1, item2, item3, nil]; 

[_items sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"itemName" ascending:YES selector:@selector(caseInsensitiveCompare:)]]]; 

我已經看過了這個問題,但一直沒能解決我的問題。

最後一行應該排序,但我不知道爲什麼它不會。

我只是想按名稱排序。任何想法?

+6

它排序陣就好了。但是你從不將任何排序的數組分配給任何東西 - 它只是落在地板上。 –

回答

3

,因爲它是不可變的,所以你需要做的,您無法編輯NSArray

_items = [_items sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"itemName" ascending:YES selector:@selector(caseInsensitiveCompare:)]]]; 
+0

總是想念小事,謝謝! – Claud

3

sortedArrayUsingDescriptors:調用返回一個NSArray實例,這就是你所謂的方法實例的整理的表示。所以:

NSArray *sortedItems = [_items sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"itemName" ascending:YES selector:@selector(caseInsensitiveCompare:)]]]; 

你也可以簡單地進一步使用你的排序描述符數組的文字語法。

NSArray *sortedItems = [_items sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"itemName" ascending:YES selector:@selector(caseInsensitiveCompare:)]]]; 

如果你想繼續突變_items NSArray實例,那麼創建是作爲一個NSMutableArray開始。

// Make sure _items instance variable is declared as an NSMutableArray  
_items =[NSMutableArray arrayWithObjects:item1, item2, item3, nil]; 

[_items sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"itemName" ascending:YES selector:@selector(caseInsensitiveCompare:)]]]; 
0

採取_items爲NSMutableArray的...

NSArray *sortedArray; 
sortedArray=[_items sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"itemName" ascending:YES selector:@selector(caseInsensitiveCompare:)]]]; 

[_items removeAllObjects]; 
[_items addObjectsFromArray:sortedArray];