在使用FBConnect的FBDialog功能时,需要有一个FBLoginDialog和一个FBStreamDialog。然而FBDialog的Delegate只有一个,因此在FBLoginDialog和FBStreamDialog中各添加了一个布尔值变量以判断需执行哪个Dialog的操作。
但是,该方法只能在两个Dialog的情况下可以使用,如果出现了两个以上的Dialog,则会使程序的结构变得极为复杂。
因此,可以改为创造一个FBDialog类,该类实现 了FBDialogDelegate协议,再在程序中实现该Dialog类的两个对象,这样就可以使不同的FBDialog去调用各自的Callback而不会再产生冲突。而且修改成类的封装后使程序的灵活性大为提高,如果今后再需要增加Dialog的数量,只需再实现一个Dialog类的对象即可,而不用对原有程序做大幅的改动。
FBDialogEventHandler.h:
#import <Foundation/Foundation.h> #import "FBConnect/FBConnect.h" @interface FBDialogEventHandler : NSObject <FBDialogDelegate> { id mTarget; SEL mSucceedHandler; SEL mCancelHandler; SEL mErrorHandler; } @property (nonatomic, assign) SEL succeedHandler; @property (nonatomic, assign) SEL cancelHandler; @property (nonatomic, assign) SEL errorHandler; - (id)initWithTarget:(id)target; @end
FBDialogEventHandler.m:
#import "FBDialogEventHandler.h" @implementation FBDialogEventHandler @synthesize succeedHandler = mSucceedHandler; @synthesize cancelHandler = mCancelHandler; @synthesize errorHandler = mErrorHandler; - (id)initWithTarget:(id)target { if (self = [super init]) { mTarget = target; } return self; } - (void)dealloc { [super dealloc]; } #pragma mark - #pragma mark FBDialogDelegate - (void)dialogDidSucceed:(FBDialog*)dialog { [mTarget performSelector:mSucceedHandler withObject:dialog]; } - (void)dialogDidCancel:(FBDialog*)dialog { [mTarget performSelector:mCancelHandler withObject:dialog]; } - (void)dialog:(FBDialog*)dialog didFailWithError:(NSError*)error { [mTarget performSelector:mErrorHandler withObject:error]; } - (BOOL)dialog:(FBDialog*)dialog shouldOpenURLInExternalBrowser:(NSURL*)url { return YES; } @end
然后,在头文件中声明:
- (void)loginDialogDidSucceed:(FBDialog *)dialog; - (void)loginDialogDidCancel:(FBDialog *)dialog; - (void)loginDialog:(FBDialog *)dialog didFailWithError:(NSError *)error; - (void)feedDialogDidSucceed:(FBDialog *)dialog; - (void)feedDialogDidCancel:(FBDialog *)dialog; - (void)feedDialog:(FBDialog *)dialog didFailWithError:(NSError *)error;
再在程序中加入:
mFBLoginHandler = [[FBDialogEventHandler alloc] initWithTarget:self]; mFBLoginHandler.succeedHandler = @selector(loginDialogDidSucceed:); mFBLoginHandler.cancelHandler = @selector(loginDialogDidCancel:); mFBLoginHandler.errorHandler = @selector(loginDialog:didFailWithError:); mFBPostFeedHandler = [[FBDialogEventHandler alloc] initWithTarget:self]; mFBPostFeedHandler.succeedHandler = @selector(feedDialogDidSucceed:); mFBPostFeedHandler.cancelHandler = @selector(feedDialogDidCancel:); mFBPostFeedHandler.errorHandler = @selector(feedDialog:didFailWithError:);