gpt4 book ai didi

iphone - 如何按升序或降序对对象的 NSMutableArray 进行排序

转载 作者:可可西里 更新时间:2023-11-01 05:30:12 27 4
gpt4 key购买 nike

我使用这段代码创建了一个对象的 NSMutableArray

- (void)viewDidLoad
{
[super viewDidLoad];
NSArray * ary1 = [NSArray arrayWithObjects:@"01/07",@"02/07",@"03/07",@"04/07",@"05/07",@"06/07",@"07/07", nil];
NSArray * ary2 = [NSArray arrayWithObjects:@"First",@"Second",@"Third",@"Forth",@"Fifth",@"Sixth",@"Seventh", nil];
NSArray * ary3 = [NSArray arrayWithObjects:@"1000",@"2000",@"3000",@"4000",@"5000",@"6000",@"7000", nil];

tableAry = [[NSMutableArray alloc] init];
for (int i=0; i<ary1.count; i++) {
//cardSummry will hold the data and give back the model to store in array and we can find that value using model
DataModel *dataModel = [[DataModel alloc] init];
dataModel.date = [ary1 objectAtIndex:i];
dataModel.name = [ary2 objectAtIndex:i];
dataModel.ammount = [ary3 objectAtIndex:i];

[tableAry addObject:dataModel];
}
}

这是我的数据模型类

.H文件

#import <Foundation/Foundation.h>

@interface DataModel : NSObject

//this variable is used to get the data from array
@property (nonatomic,strong) NSString *date;
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *ammount;

//this method will genarate a data model which will be added to array for future use
+ (id)cardSummary:(NSString*)date name:(NSString*)name ammount:(NSString*)ammount;
@end

.M文件

#import "DataModel.h"

@implementation DataModel

@synthesize date,name,ammount;

//this method will genarate a data model which will be added to array for future use
+ (id)cardSummary:(NSString*)date name:(NSString*)name ammount:(NSString*)ammount
{
DataModel *dataModel = [[self alloc] init];

[dataModel setDate:date];
[dataModel setAmmount:ammount];
[dataModel setName:name];

return dataModel;
}

@end

现在我想根据我看到的数组中的名称对其进行排序 this SO 中的问题看起来像我的,并使用它的答案代码来解决我的问题,但它对我不起作用,这是

[tableAry sortUsingDescriptors:
[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]]];

NSLog(@"tableAry : %@",tableAry);

那么我怎样才能对我的数组进行排序

更新

正如@Martin R 和@Rick 所说,我已经分配了我的数组,但现在我遇到了这个错误。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[DataModel caseInsensitiveCompare:]: unrecognized selector sent to instance 0x7550850'

最佳答案

您还可以使用 NSSortDescriptor

NSSortDescriptor* sortDes = [[NSSortDescriptor alloc] initWithKey:@"your key" ascending:YES];
[_array sortUsingDescriptors:[NSArray arrayWithObject:sortDes]];

试一试。

关于iphone - 如何按升序或降序对对象的 NSMutableArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17763726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com