iosobjective-cuilocalizedcollation

Dynamic selector using UILocalizedIndexedCollation sectionForObject:collationStringSelector


I need to set the selector dynamically when using UILocalizedIndexedCollation In my app, I have the following code:

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

        theObject.section=(int)section;
    }

mainTitle is one of many properties in myObject. However, I want the selector to by any string. I followed hint from this site: What is the role of selector in UILocalizedIndexedCollation's sectionForObject:(id)object collationStringSelector:(SEL)selector method, and introdused following:

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

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

This caused crash with error: [MyObject myString]: unrecognized selector sent to instance ...

What is the correct way to add a dynamic selector?


Solution

  • I'm assuming you are trying to handle sorting on different properties of MyObject.

    The error you reported is happening because the MyString method needs to be part of the MyObject class, not the class using the UILocalizedIndexedCollation.

    One dynamic way to specific the selector would be something like this:

    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;
    }