簡體   English   中英

如何對自定義NSArray排序?

[英]How to sort a custom 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:)]]];

我已經查找了問題,但無法解決我的問題。

最后一行應該對它進行排序,但我不知道為什么不會。

我只想按名稱排序。有什么想法嗎?

您無法編輯NSArray因為它是不可變的,因此您需要執行以下操作:

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

調用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實例,則create是作為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:)]]];

將_items作為NSMutableArray ...

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM