Objective C - “Duplicate declaration of method” compilation error

為{幸葍}努か 提交于 2019-12-06 11:44:27

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.

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!