Passing a @selector dynamically
Depending on the result from ABPersonGetSortOrdering(), I want to sort a UILocalizedIndexCollation by first name or last name.
I'm having problems switching the @selector used for the collationStringSelector parameter.
It'd be very easy to just write this verbosely:
NSArray *sortedSubarray; if (ABPersonGetSortOrdering() == 0) { sortedSubarray = [collation sortedArrayFromArray:[sections objectAtIndex:section] collationStringSelector:@selector(fname)]; } else { sortedSubarray = [collation sortedArrayFromArray:[sections objectAtIndex:section] collationStringSelector:@selector(lname)]; }
I've tried something like this with no luck:
SEL sorter = ABPersonGetSortOrdering() == 0 ? NSSelectorFromString(@"fname") : NSSelectorFromString(@"lname"); sortedSubarray = [collation sortedArrayFromArray:[sectio开发者_如何学Pythonns objectAtIndex:section] collationStringSelector:@selector(sorter)];
I've tried out other ideas as well, and nothing seems to be working.
Is there a better way to pass a selector name dynamically?
You are almost there, just remove the @selector()
part from around sorter
:
sortedSubarray = [collation sortedArrayFromArray:[sections objectAtIndex:section] collationStringSelector:sorter];
精彩评论