问题
I have this piece of code:
- (id) getSearchSuggestions:(NSString*)q;
- (NSOperationQueue*) getSearchSuggestions:(NSString*)q callback:(id<UserDelegate>)callback;
- (id) getSearchSuggestions;
- (NSOperationQueue*) getSearchSuggestions:(id<UserDelegate>)callback;
And I Xcode keeps showing me an error on the last line:
Duplicate declaration of method "getSearchSuggestions"
Why? It seems to me that the signatures are all different.
回答1:
This signature:
- (id) getSearchSuggestions:(NSString*)q;
Is identical to this signature:
- (NSOperationQueue*) getSearchSuggestions:(id<UserDelegate>)callback;
All object pointers are id
. So both of these are methods that take an object and return an object.
Examples of better names would be:
- (id)searchSuggestionsForQueryString:(NSString*)q; // Or ForTag, or whatever "q" is
- (NSOperationQueue*)searchOperationQueueForQuery:(NSString*)q callback:(id<UserDelegate>)callback;
- (id)fetchSearchSuggestions;
- (NSOperationQueue*)searchOperationQueueWithCallback:(id<UserDelegate>)callback;
It's not exactly clear why you return an operation queue here, but this is the kind of name you'd use for a method that did that.
回答2:
Think of the corresponding selectors:
- (id) getSearchSuggestions:(NSString*)q;
getSearchSuggestions:
- (NSOperationQueue*) getSearchSuggestions:(NSString*)q callback:(id<UserDelegate>)callback;
getSearchSuggestions:callback:
- (id) getSearchSuggestions;
getSearchSuggestions
- (NSOperationQueue*) getSearchSuggestions:(id<UserDelegate>)callback;
getSearchSuggestions:
As you can see, the first and the last method have the same selector, hence the duplicate method declaration error. You need to disambiguate them by changing their names.
回答3:
it is because these two have the same selector:
- (id) getSearchSuggestions:(NSString*)q;
- (NSOperationQueue*) getSearchSuggestions:(id<UserDelegate>)callback;
you must choose unique names for selectors.
回答4:
You seem to be trying to overload methods like in Java. Objective-C doesn't have this capability (it basically doesn't work well with Objective-C's more dynamic type system). In Objective-C, the selector for a method is the entirety of how it is identified. Think of it as a message: "Call the method named getSearchSuggestions:
and give it these arguments." There can't be multiple methods in the class called getSearchSuggestions:
because the selector is the only thing the message dispatch system has to determine which method is called.
来源:https://stackoverflow.com/questions/7374277/objective-c-duplicate-declaration-of-method-compilation-error