动态传递@selector

4
根据 ABPersonGetSortOrdering() 的结果,我想通过名字或姓氏对 UILocalizedIndexCollation 进行排序。
我在切换 collationStringSelector 参数所使用的 @selector 上遇到了问题。
很容易就可以写出冗长的代码:
NSArray *sortedSubarray; if (ABPersonGetSortOrdering() == 0) { sortedSubarray = [collation sortedArrayFromArray:[sections objectAtIndex:section] collationStringSelector:@selector(fname)]; } else { sortedSubarray = [collation sortedArrayFromArray:[sections objectAtIndex:section] collationStringSelector:@selector(lname)]; }
我尝试过类似这样的代码但没有成功:
SEL sorter = ABPersonGetSortOrdering() == 0 ? NSSelectorFromString(@"fname") : NSSelectorFromString(@"lname"); sortedSubarray = [collation sortedArrayFromArray:[sections objectAtIndex:section] collationStringSelector:@selector(sorter)];
我还尝试了其他想法,但似乎都没有起作用。
是否有更好的方法来动态传递选择器名称呢?
1个回答

7

你已经快完成了,只需从 sorter 周围删除 @selector() 部分即可:

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

1
太棒了!我一直在努力不问问题...但至少我接近了!感谢您的快速回复。 - djibouti33

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接