在C/Objective-C中是否有来自Perl的"<=>"运算符的替代?

Mar*_*rov 2 perl compare objective-c

我正在实现一些自定义的NSArray排序选择器,我想知道是否有类似C/Objective-C中的<=>运算符?

我有这个:

if (self.count == otherObject.count) return 0;
return (self.count > otherObject.count)? 1 : -1;
Run Code Online (Sandbox Code Playgroud)

并且很想拥有(如在Perl中)

return self.count <=> otherObject.count;
Run Code Online (Sandbox Code Playgroud)

Mat*_*man 7

也许这个compare:方法正是你要找的?NSString,NSNumber等实现它.Cocoa中所有类似比较的方法都返回一个NSComparisonResult:

enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
Run Code Online (Sandbox Code Playgroud)

因此,您可以直接使用返回的整数值.假设count你的问题是NSNumber你可以做的:

return [self.count compare:otherObject.count];
Run Code Online (Sandbox Code Playgroud)

如果您的情况仅限于数字,并且您只想使用操作员,则可以使用旧的减号.但要注意整数溢出!:

return self.count - otherObject.count;
Run Code Online (Sandbox Code Playgroud)