问题
I am a beginner of iOS development and while going through this document (iOS Developer Guide about configuring a TableView with Indexed List) I came across this:
// Listing 4.7
for (State *theState in statesTemp) {
NSInteger sect = [theCollation sectionForObject:theState collationStringSelector:@selector(name)];
theState.sectionNumber = sect;
}
I could not figure out the selector (@selector(name)
) and its purpose, nor could I find the method with the name passed in the selector i.e. name
. I googled for examples to find a better explanation, and came across this example.
In the code listing, there is a statement which is a method call:
self.tableData = [self partitionObjects:objects collationStringSelector:@selector(title)];
now the selector is called title
. I have not been able to find a better explanation, and my question is what is the purpose of this selector and the method referred by this selector, and what should it do and return.
回答1:
In general
With the @selector(title:)
you define which method will be called.
in my example it will call
- (void) title:(id)someObject {}
Be carefull with the semicolon at the end! If you have a semicolon at the end you method will have parameters like mine above.
Your code states just @selector(title)
and will call a method title without a parameter like this:
- (void)title {}
Specific to UILocalizedIndexCollation
The docs state:
selector
A selector that identifies a method returning an identifying string for object that is used in collation. The method should take no arguments and return an NSString object. For example, this could be a name property on the object.
So i would suggest you implement it like this
self.tableData = [self partitionObjects:objects collationStringSelector:@selector(title)];
...
- (NSString *)title {
NSString *title;
// some code to fill title with an identifier for your object
return title;
}
回答2:
Try replace the title
with self
:
self.tableData = [self partitionObjects:objects collationStringSelector:@selector(self)];
worked for me
来源:https://stackoverflow.com/questions/11609440/what-is-the-role-of-selector-in-uilocalizedindexedcollations-sectionforobject