Let's say I have a class UploadManager
and I create an instance of it in my ViewController
. UploadManager.m
has a method -(void)requestData
-(void)requestData
{
HTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] init];
[operation setCompletionBlockWithSuccess:^(HTTPRequestOperation *operation, id responseObject){
// Do something here
}];
[operation start];
}
Now I can call the requestData
method from my instance of UploadManager
in ViewController.m
, but I'd like to do something with the responseObject
inside of ViewController.m
once the completion block has fired. What's the best way of doing this? I assume I could make a delegate method but I'm wondering if there's a better solution. Thanks.
You can use blocks structure for that
-(void)requestDataWithHandler:(void (^)(id responceObject))handler
{
HTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] init];
[operation setCompletionBlockWithSuccess:^(HTTPRequestOperation *operation, id responseObject){
// Do something here
if(handler)
{
handler(responceObject)
}
}];
[operation start];
}
In another class
[uploadManager requestDataWithHandler:^(responceObject) {
// here work with responeObject
}];
The block-based approach will certainly work. If you want an alternate approach to blocks, you could use NSNotifications
as follows:
-(void)requestDataWithHandler:(void (^)(id responseObject))handler
{
HTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] init];
[operation setCompletionBlockWithSuccess:^(HTTPRequestOperation *operation, id responseObject){
// You'll probably want to define the Notification name elsewhere instead of saying @"Information updated" below.
[[NSNotificationCenter defaultCenter] postNotificationName:@"Information updated" object:nil];
}];
[operation start];
}
Elsewhere in ViewController.m
:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomethingUponUpdate) name:@"Information updated" object:nil];
}
-(void)dealloc
{
// Don't forget to remove the observer, or things will get unpleasant
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)doSomethingUponUpdate
{
// Something
}
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.