How to call a delegate's function without gett

2019-05-28 04:54发布

问题:

In the apps I worked on, I often found such lines of code

[delegate aFunction];

that generated the "instance method "aFunction" not found (return type defaults to id)" warning

Now, I did a bit of research on SO and found out that the warning can be removed by declaring the function for cases when you call it on self ([self aFunction];), but none of the answers said anything about my case, when I use a delegate.

So, long story short, what can I do to correctly call a delegate's method inside another class? Things appear to work fine, so this is not a major issue, but a warning means I'm not doing something completely correct so I would like to learn what's the best practice for such cases

Thank you for your help in advance!

回答1:

So, if I'm understanding you correctly, your issues can be taken away by declaring your protocol as follows:

@class SomeClass;
@protocol SomeClassDelegate <NSObject>
@required
- (void)thisObjectDidSomething:(SomeClass*)instance;
@optional
- (void)thisObjectDidSomethingUnimportant:(SomeClass*)instance;
@end

Then your delegate ivar and property look like this (use assign instead of weak if you're not using ARC):

@interface SomeClass () {
    __weak id<SomeClassDelegate> delegate_;
}
@property (weak) id<SomeClassDelegate> delegate;

And in the .h file of any class that's going to implement that protocol, do this:

@interface TCReader : NSObject <SomeClassDelegate> {

}

Since it's safe to call selectors on nil, for required methods, you can just:

[self.delegate thisObjectDidSomething:self]

But for optional methods, you'd better:

if ([self.delegate respondsToSelector:@selector(thisObjectDidSomethingUnimportant:)]) {
    [self.delegate thisObjectDidSomethingUnimportant:self]
}

The main point here is that by declaring and making use of a protocol, you let XCode know that those methods are defined for objects implementing the protocol. If you require that your delegate implement that protocol, then Xcode knows that your delegate has those methods defined.