objective-c - 如何比较对象属性然后使用 ( sortusingselector :@selector)?

标签 objective-c

我正在尝试编写一个简单的函数 == "compareGPA"来比较两个学生的 GPA,然后使用选择器按降序对它们进行排序:[array sortUsingSelector:@selector(compareGPA:)];

我试过用两种不同的方式编写函数,但没有任何效果,

第一种方式:

+(NSComparisonResult) compareGPA: (Student *) OtherStudent{ 

Student *tmp =[Student new];

if ([OtherStudent getGpa] < [tmp getGpa]){

return (NSComparisonResult) tmp;

}

if([tmp getGpa] < [OtherStudent getGpa])

{ return (NSComparisonResult) OtherStudent; }


}

第二种方式:

+(NSComparisonResult) compareGPA: (Student *) OtherStudent{


NSComparisonResult res;


res = [[self getGpa] compare: [OtherStudent getGpa]];

return res;

Switch (res)
{

case NSOrderedAscending:

return NSOrderedDescending;

break;

case NSOrderedDescending:

return NSOrderedAscending;

break;

default:

return NSOrderedSame;

break;

}

}

输出:无

有什么建议吗??

最佳答案

你应该做你的caparison方法

+(NSComparisonResult) compareGPA: (Student *) OtherStudent

一个实例方法(不是类方法,+ 变成 -),这样它将接收者的 GPA 与 OtherStudent 的 GPA 进行比较),就像这样

-(NSComparisonResult) compareGPA: (Student *) OtherStudent {

     // if GPA is a float int double ...
     if ([OtherStudent getGpa] == [self getGpa] 
         return NSOrderedSame;
     if ([OtherStudent getGpa] < [self getGpa]){
         return NSOrderedAscending;
     return NSOrderedDescending;

     // if GPA is an object which responds to the compare: message
     return [[self getGPA] compare:[OtherStudent getGPA]]

}

然后使用选择器 @selector(compareGPA:)

对您的 Student 对象数组进行排序

关于objective-c - 如何比较对象属性然后使用 ( sortusingselector :@selector)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8136564/

相关文章:

c# - 将 C# 泛型方法转换为 Objective-C

ios - ios自动布局动态UILabel高度

ios - 检测对象的至少一个属性是否被修改

ios - UICollectionView 单元格之间的距离不变

objective-c - Cocoa 中处理字符串的整数转换

ios - Xcode 自动将信息图标/"Accessory Button"添加到我的表格单元格

objective-c - swift 1.2 : Implement optional property from Objc protocol

ios - Objective-C 为对象的每个方法添加功能

objective-c - 从 C++ 循环启动 Cocoa GUI 并传递引用

ios - 如何设置一个简单的委托(delegate)来在两个 View Controller 之间进行通信?