Passing @selector dynamically

Depending on the result from ABPersonGetSortOrdering (), I want to sort UILocalizedIndexCollation by first or last name.

I'm having problems with the @selector switch used for the collationStringSelector parameter.

It would be very simple to write it verbose:

  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 tried something like this with no luck:

  SEL sorter = ABPersonGetSortOrdering () == 0?  NSSelectorFromString (@ "fname"): NSSelectorFromString (@ "lname");
 sortedSubarray = [collation sortedArrayFromArray: [sections objectAtIndex: section] collationStringSelector: @selector (sorter)];

I also tried other ideas and nothing works.

Is there a better way to pass a selector name dynamically?

+4
source share
1 answer

You are almost there, just remove the @selector() from the sorter :

 sortedSubarray = [collation sortedArrayFromArray:[sections objectAtIndex:section] collationStringSelector:sorter]; 
+7
source

Source: https://habr.com/ru/post/1344052/


All Articles