>我创建了一个自定义类,NetworkManager。它有两个可选的委托方法。它工作得很好,但是,问题是当有多个NetworkManager
实例时如何执行委托方法。这是我的代码片段;
NetworkManager.h
@protocol NetworkManagerDelegate <NSObject>
@optional
//call back for success message
-(void)handleSuccessMessageWithDictionary:(NSDictionary *) jsonDictionary;
//call back for fail message
-(void)handleFailureMessageWitDictionary:(NSDictionary *) jsonDictionary;
@end
@interface NetworkManager : NSObject
@property (nonatomic,assign) id<NetworkManagerDelegate> delegate;
@end
然后在我的视图控制器中,我有:
#pragma-mark NetowrkManager Delegate
-(void)handleFailureMessageWitDictionary:(NSDictionary *)jsonDictionary{
//failure
}
-(void)handleSuccessMessageWithDictionary:(NSDictionary *)jsonDictionary{
//success
}
这适用于一个NetworkManager
实例,但是如何区分两个实例呢?
例如
#pragma-mark NetowrkManager Delegate
-(void)handleFailureMessageWitDictionary:(NSDictionary *)jsonDictionary{
//if its networkManagerA do
// method A
//else if its networkManagerB do
//method B
-(void)handleSuccessMessageWithDictionary:(NSDictionary *)jsonDictionary{
//if its networkManagerA do
// method A
//else if its networkManagerB do
//method B
}
任何建议将不胜感激!
将委托对象的实例传递回委托是正常的;请参阅UITableViewDelegate
方法,例如:
- (BOOL) tableView:(UITableView *)tableView
shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath;
这样,单个委托对象可以在多个实例上工作。
将实例传回委托,类似于委托UITableView
的工作方式:
-(void)handleSuccessMessageWithDictionary:(NSDictionary *)jsonDictionary manager:(NetworkManager *)manager
然后,只需从发送回调的实例传递self
:
[self handleSuccessMessageWithDictionary:json manager:self];
在创建 NetworkManager.h 的对象时,设置一个属性,以确定哪个类创建了其对象。在委托方法中,检查属性并相应地执行操作。在NetworkManager.h中创建一个属性@property(非原子)id类名;并在创建 NetworkManager.h 的对象时设置它:NETWORKManager.className = [self class];现在在-(void)handleFailureMessageWitDictionary:(NSDictionary *)jsonDictionary{if (_className == A){...}否则如果 (_className == B){...}}