简体   繁体   中英

Simple iOS delegate/callback

I have a simple ViewController. In the .m file I put #import "Manager.h"

There is a button and when it is clicked the following code is executed:

Manager* manager = [[Manager alloc] init];
NSString* str = [manager doit];
NSLog(@"str = %@", str);

Manager is a subclass of NSObject. In Manager.m I have this method:

- (NSString*)doit{
    return @"did it";
}

Great. All this works as expected.

What I need is, if possible and if a good practice, to send/make Manager to understand, that from the method doit another method in ViewController should be called. Some kind of callback/delegate. How do I accomplish this?

When I call [manager doit]; I also want to inform that a method in ViewController should be executed. I hope you understand what I mean otherwise I can write some more details. Thanks

Yes you could use delegate, Your implementation of the delegate in the Manager object should look like so:

@protocol managerDelegate <NSObject>

-(void)doSomthingAndGetThisString: (NSString *)stringText;

@end

@interface Manager : NSObject
@property (nonatomic,strong) id <managerDelegate>delegate;
@end

As you can see, the Manager object claims his delegate protocol in the header interface, So any class could sign on it, And if they do, they should preform the method "doSomthingAndGetThisString".

Whenever "Manager" object chooses to fire the delegate methods he will call it like so:

- (NSString*)doit{
    //Call my delegate:
    [self.delegate doSomthingAndGetThisString:@"Passing this stringt to my delegate"];
    return @"did it";

}

ViewController: ViewController needs to keep a property of the manager object:

@property (nonatomic,strong) Manager *myManager;

And Now when you allocate "myObject", ViewController should "sign" to preform the Delegate like so:

  _myManager = [Manager new];
    _myManager.delegate = self;

And of course have the method:

-(void)doSomthingAndGetThisString: (NSString *)stringText;

That will call whenever "Manager" object firs it.

Hope this helps

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