Reputation: 10264
I use several NSComparators in my iOS app which compare objects by NSString or NSNumber properties. This is fairly easy because NSString has caseInsensitiveCompare:
and NSNumber has compare:
. How do I compare bools or ints though? For booleans, code could get pretty tangled quite quickly, as my comparision functions take a (bool)ascending
parameter. I've noticed Objective C often has obscure global functions for this type of thing.
Currently I'm using this code to compare booleans:
NSComparator comp = ^(id id1, id id2) {
ListItem *comp1 = nil,
*comp2 = nil;
if([id1 isKindOfClass:[ListItem class]]){
if(ascending){
comp1 = (ListItem*)id1;
comp2 = (ListItem*)id2;
}else{
comp1 = (ListItem*)id2;
comp2 = (ListItem*)id1;
}
}
if(h1!=nil && h2!=nil){
if((h1.isInBasket && h2.isInBasket) || (!h1.isInBasket && !h2.isInBasket)){
return 0;
} else if(h1.isInBasket && !h2.isInBasket) {
return 1;
} else {
return -1;
}
} else {
return 0;
}
}
Upvotes: 0
Views: 207
Reputation: 53010
Bools (BOOL
, Boolean
) and integers (int
, long
, unsigned
, etc.) are just plain C integral types and you compare them with the standard C comparison operators <
, >
, ==
etc. Same holds for char
(also an integral type), float
, etc. and the named variants such as NSInteger
.
Upvotes: 2