【问题标题】:Dynamic selector using UILocalizedIndexedCollation sectionForObject:collationStringSelector使用 UILocalizedIndexedCollat​​ion sectionForObject:collat​​ionStringSelector 的动态选择器
【发布时间】:2015-08-02 16:16:27
【问题描述】:

我需要在使用 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]: unrecognized selector sent to instance ...

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

【问题讨论】:

    标签: ios objective-c uilocalizedcollation


    【解决方案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;
    }
    

    【讨论】:

    • 我会避免使用 NSSelectorFromString 并且只有一个返回 SEL 的函数,即@selector(mainTitle),这样你就可以从编译器获得一些保护
    猜你喜欢
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    相关资源
    最近更新 更多