2013-05-28 2 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

TAKE _items как NSMutableArray ...

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

[_items removeAllObjects]; 
[_items addObjectsFromArray:sortedArray]; 
Смежные вопросы