如何按字母顺序对 NSMutable 数组中的自定义对象字段进行排序?
我有一个自定义对象,例如:
#import <Foundation/Foundation.h>
@interface Store : NSObject{
NSString *name;
NSString *address;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *address;
@end
我有一个包含 Store 对象的 NSMutableArray (storeArray) 数组:
store1 = [[Store alloc] init];
store1.name = @"Walmart";
store1.address = @"walmart address here..";
store2 = [[Store alloc] init];
store2.name = @"Target";
store2.address = @"Target address here..";
store3 = [[Store alloc] init];
store3.name = @"Apple Store";
store3.address = @"Apple store address here..";
//add stores to array
storeArray = [[NSMutableArray alloc] init];
[storeArray addObject:store1];
[storeArray addObject:store2];
[storeArray addObject:store3];
我的问题是如何按商店名称对数组进行排序?我知道我可以使用以下行按字母顺序对数组进行排序:
[nameOfArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
How can I apply this to the store name of my Store class?
I have a custom object like:
#import <Foundation/Foundation.h>
@interface Store : NSObject{
NSString *name;
NSString *address;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *address;
@end
I have an array of NSMutableArray (storeArray) containing Store objects:
store1 = [[Store alloc] init];
store1.name = @"Walmart";
store1.address = @"walmart address here..";
store2 = [[Store alloc] init];
store2.name = @"Target";
store2.address = @"Target address here..";
store3 = [[Store alloc] init];
store3.name = @"Apple Store";
store3.address = @"Apple store address here..";
//add stores to array
storeArray = [[NSMutableArray alloc] init];
[storeArray addObject:store1];
[storeArray addObject:store2];
[storeArray addObject:store3];
My question is how can I sort the array by the store name? I know I can sort an array alphabetically by using this line:
[nameOfArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
How can I apply this to the store name of my Store class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
相关文档:
Related documentation:
Regexident 的回答 基于 NSArrays,NSMutableArray 相应的就地排序将是
-sortUsingDescriptors:
现在
storeArray
本身将被排序。Regexident's answer is based on NSArrays, the corresponding in-place sorting for NSMutableArray would be
-sortUsingDescriptors:
Now
storeArray
it-self will be sorted.