我们说我有一个班级UploadManager
,我在ViewController
创建了一个实例。 UploadManager.m
有一个方法-(void)requestData
-(void)requestData
{
HTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] init];
[operation setCompletionBlockWithSuccess:^(HTTPRequestOperation *operation, id responseObject){
// Do something here
}];
[operation start];
}
现在,我可以在requestData
中的UploadManager
实例中调用ViewController.m
方法,但我想对responseObject
内的ViewController.m
做一些事情。一旦完成块被触发,{1}}这样做的最佳方法是什么?我假设我可以制作代理方法,但我想知道是否有更好的解决方案。感谢。
答案 0 :(得分:3)
您可以使用块结构
-(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];
}
在另一个班级
[uploadManager requestDataWithHandler:^(responceObject) {
// here work with responeObject
}];
答案 1 :(得分:1)
基于块的方法肯定会奏效。如果您想要替代块的方法,可以使用NSNotifications
,如下所示:
-(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];
}
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
}