第 1 步:
在您的 App Delegate .h 文件中,您需要像这样声明一个协议:
@protocol AppConnectionDelegate <NSObject>
@required
-(void)connectionFinished:(NSObject*)outObject;
@end
在同一个文件中,像这样添加一个 ivar:
id *delegate;
将 ivar 声明为属性:
@property (nonatomic, assign) id<AppConnectionDelegate> delegate;
在 App Delegate .m 文件中,合成 ivar:
@synthesize delegate;
在 App Delegate .m 文件中,在 connectionDidFinishLoading 上执行:
if([self.delegate respondsToSelector:@selector(connectionFinished:)])
{
[self.delegate connectionFinished:objectYouWantToSend];
}
在视图控制器的 .h 文件中,通过导入对应用委托文件的引用来实现 AppConnectionDelegate:
#import "AppDelegate_iPhone.h" //if using iPhone
#import "AppDelegate_iPad.h" //if using iPad
在同一个文件中,在接口声明的第一行末尾做:
@interface AppDelegate_iPhone : AppDelegate_Shared <AppConnectionDelegate>
相应地声明 ivars:
AppDelegate_iPhone *appDelegate; //if using iPhone
AppDelegate_iPad *appDelegate; // if using iPad
在 viewDidLoad() 的 viewcontroller 的 .m 文件中,使用以下命令获取对应用委托的引用:
如果是 iPhone;
appDelegate = (AppDelegate_iPhone*)[[UIApplication sharedApplication] delegate];
如果是 iPad:
appDelegate = (AppDelegate_iPad*)[[UIApplication sharedApplication] delegate];
然后将 viewcontroller 设置为 viewDidLoad() 中的委托:
appDelegate.delegate = self;
现在你只需在.m文件中实现connectionFinished方法:
- (void)connectionFinished:(NSObject*)incomingObject
{
//Do whatever you want here when the connection is finished. IncomingObject is the object that the app delegate sent.
}
现在,无论何时调用您的应用代理的 connectionDidFinishLoading,都会通知视图控制器。
[如果您已使用 connectionFinished 回调,最好设置 appDelegate.delegate = nil]
这是久经考验的。如有疑问,请发表评论......
--EDIT--
这是 NSNotification 的强大替代方案。我根据要求使用两者。我用来决定使用 NSNotification 还是使用协议的委托回调的过程很简单:
对于通知:
一个发送者,多个听众。
发送者和侦听者之间不可能有引用。
不需要发送复杂/多个对象
对于使用协议的委托回调:
一位发件人,有限的(通常是 1 个)听众。
发送者和监听者之间的引用是可能的。
要发送复杂/多个对象(例如,需要发送的响应对象)
我知道通过通知发送对象是可能的,但我更喜欢协议。
--编辑--