我的主视图控制器如何知道Web服务调用何时完成

时间:2012-06-15 19:11:05

标签: iphone ios web-services ipad delegates

您好我有一个基于Web服务的应用程序,它将与我们的服务器交换数据。由于我有一个专门的课程来完成我的工作,主视图控制器实际上每次都会调用该工作者。工作人员自己知道连接何时完成,因为它是NSURLConnectionDelegate。但是,无论何时完成工作,我都需要通知主视图控制器。 worker是主视图控制器的委托,因此它知道何时需要开始工作。请帮帮我。

4 个答案:

答案 0 :(得分:2)

你应该做相反的事情。

首先将您的worker对象声明为主视图控制器的成员(当然,将其设为属性),然后从主视图控制器,您只需调用[self.worker sendRequstToServer]发送请求即可。

其次,在主视图控制器中,无论您初始化工作对象,都不要忘记放置self = worker.delegate

第三,在你的工人类中声明一个委托方法,例如-(void)webServiceCallFinished(),并在你的工作人员[self.delegate webServiceCallFinished]中调用-connectionDidFinishLoading()(如果你在-parserDidEndDocument()你可能想做正在使用NSXMLParer来解析xml)

最后,您想要将主视图控制器声明为您的工作类的委托并实现-webServiceCallFinished()

希望这有帮助。

答案 1 :(得分:2)

您可以通过两种方式实现:

方法#1:

用户本地通知。 在主类中,以下列方式将一个观察者添加到LocalNotification Center中。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jobDone) name:@"WORKERJOBOVER" object:nil];

当工作完成后,在工人类中,发布nofitication来激活选择器:

[[NSNotificationCenter defaultCenter] postNotificationName:@"WORKERJOBOVER" object:nil];

方法#2:

您可以创建工人类的协议,并在协议中添加一个方法,当您在工作中完成工作时,可以在代理上调用该方法。

<强> WorkerClass.h

//WorkerClass.h

@protocol WorkerDelegate

@interface WorkerClass: NSObject

@property (nonatomic, assign) id<WorkerDelegate> delegate

- (void)JobInProcess;
@end


@protocol WorkerDelegate
- (void)MyJobIsDone;
@end

<强> WorkerClass.m

//WorkerClass.m

@implementation WorkerClass
@synthesize delegate = _delegate;

- (void)JobInProcess
{
    //When job over this will fire callback method in main class
    [self.delegate MyJobIsDone];
}

<强> MainClass.h

    //MainClass.h
#import WorkerClass.h

@interface MainClass: NSObject <WorkerDelegate>


@end

<强> MainClass.m

//MainClass.m

@implementation MainClass

- (void)MyJobIsDone
{
    //Do whatever you like
}
@end

答案 2 :(得分:1)

在主视图控制器的viewDidLoad:中,将其设置为[NSNotificationCenter defaultCenter]的通知观察者:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webServiceContacted:) name:@"webServiceConnectionSuccessful" object:nil];

然后,当您的数据与服务器成功互换后,在网络完成块中发布通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"webServiceConnectionSuccessful" object:nil];

webServiceContacted:看起来像这样:

-(void)webServiceContacted:(NSNotification *)note
{
    //do stuff here
}

答案 3 :(得分:0)

我会向后台工作人员发出一条通知,告知您可以从主视图控制器中监听

在您的视图中,当您想要收听时添加以下内容。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(operationComplete:) name:@"operationComplete" object:nil];

在后台查看通知事件已完成。

[[NSNotificationCenter defaultCenter] postNotificationName:@"operationComplete" object:nil];

最后不要忘记删除观察者     [[NSNotificationCenter defaultCenter] removeObserver:self];

相关问题