使用UILocalizedIndexedCollat​​ion sectionForObject的动态选择器:collat​​ionStringSelector

时间:2015-08-02 16:16:28

标签: ios objective-c uilocalizedcollation

我需要在使用UILocalizedIndexedCollat​​ion时动态设置选择器 在我的应用程序中,我有以下代码:

 UILocalizedIndexedCollation *indexedCollation=[UILocalizedIndexedCollation currentCollation];
    for (MyObject *theObject in objects)
    {
        NSInteger section;
        section=[indexedCollation sectionForObject:theObject collationStringSelector:@selector(mainTitle)];

        theObject.section=(int)section;
    }

mainTitle是myObject中的众多属性之一。 但是,我想通过任何字符串选择器。我跟着这个网站的提示:  What is the role of selector in UILocalizedIndexedCollation's sectionForObject:(id)object collationStringSelector:(SEL)selector method,并介绍了以下内容:

-(NSString*)myString
{
    NSString* myString;
    myString = // whatever code to set new string belonging to myObject
    return myString;
}

 section=[indexedCollation sectionForObject:theObject collationStringSelector:@selector(myString)];

这导致崩溃并出现错误:[MyObject myString]:无法识别的选择器发送到实例...

添加动态选择器的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我假设您正在尝试处理MyObject的不同属性的排序。

您报告的错误正在发生,因为MyString方法需要成为MyObject类的一部分,而不是使用UILocalizedIndexedCollation的类。

特定选择器的一种动态方式是这样的:

UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];

NSString *propertyName;
if (someConditionA) {
    propertyName = @"mainTitle";
} else if (someConditionB) {
    propertyName = @"description"; // whatever property you need
} else {
    propertyName = @"name"; // some default property you want to use
}
SEL propertySelector = NSSelectorFromString(propertyName);

for (MyObject *theObject in objects) {
    NSInteger section = [indexedCollation sectionForObject:theObject collationStringSelector:propertySelector];
    theObject.section = section;
}