简体   繁体   中英

What is the difference between following delegate method call?

I am confused about these delegate method calls.

Which one is the correct way of calling the delegate method?

@protocol XYZDelegate <NSObject>

@required
- (void)someMethod:(id)someObject;
@end

method 1:

- (void)someButtonAction:(UIButton *)sender {

    if([self.delegate && [self.delegate respondsToSelector:@selector(someMethod:)]]) {

    [self.delegate someMethod:sender];

    }

}

method 2:

- (void)someButtonAction:(UIButton *)sender {

    if([self.delegate && [self.delegate respondsToSelector:@selector(someMethod:)]]) {

    [self.delegate performSelector:@selector(someMethod:) withObject:sender];

    }

}

They are both pretty much the same. They will result in the same outcome.

The second is slightly less efficient.

What I would change is the line...

if([self.delegate && [self.delegate respondsToSelector:@selector(someMethod:)]]) {...

The method someMethod: is required by the protocol.

So you can remove it completely...

- (void)someButtonAction:(UIButton *)sender {
    [self.delegate someMethod:sender];    
}

And it will still work. You can send a message to nil and it just won't do anything. If the delegate is not nil then by definition it will respond to the selector.

If the delegate object does not conform to the method then you will get a compiler error (or maybe just a warning?).

Anyway, that should suffice.

Just as a side note. I personally prefer the first method and if there is more than one parameter then you would have to call it that way to be able to pass the parameters in corrcetly.

The difference is one calls the delegate method directly, while the other uses the runtime, through performSelector , to do so dynamically.

The latter is less efficient and pointless, but the results are the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM