你絕對可以做得更好,刪除委託模式,使用塊。
一個基於塊的屬性添加到您的TagsScrollView .h文件中
@property (copy, nonatomic) void (^tagPressedBlock)(id sender, NSString *query);
在
。M檔添加相關的回調
- (void)tagPressed:(id)sender {
if (_tagPressedBlock) {
_tagPressedBlock(sender, self.query); // I'm assuming that the query is your iVar
}
}
分配這樣
tagsScrollView.tagPressedBlock = ^(id sender, NSString *query) {
// do stuff with those parameters
}
這對屬性「做得更好」
至於如何壓制事件代碼傳遞到MainVC
類,你應該使用NSNotificationCenter。
將通知名稱定義在全局可見的地方,例如我建議創建一個Defines.h文件並將其包括在Prefix.pch文件中。
無論如何,定義通知名稱:
static NSString *const TagPressedNotification = @"TagPressedNotification";
下一步在執行-tagPressed:
發佈通知和封裝有價值的信息到用戶信息詞典:
- (void)tagPressed:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:TagPressedNotification object:nil userInfo:@{@"sender" : sender, @"query" : self.query, @"scrollView" : self.tagScrollView}];
//.. code
}
下一頁添加MainVC
作爲該通知的觀察員:
MainVC.m
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(tagPressed:)
name:TagPressedNotification
object:nil];
}
,實施您的MainVC -tagPressed:
方法
- (void)tagPressed:(NSNotification *)notification {
id sender = notification.userInfo[@"sender"];
NSString *query = notification.userInfo[@"query"];
TagScrollView *scrollView = notification.userInfo[@"scrollView"];
if (scrollView == myScrollView) { // the one on your mainVC
// do stuff
}
}
添加,不要忘記清理自己了通知中心的寄存器:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
容易
編輯
我想你也應該傳遞滾動視圖,這是發件人,因爲你的mainVC也包含該滾動視圖。編輯代碼
另一個編輯
創建枚舉在Defines.h定義文件
enum {
TagSenderTypeFeed = 1,
TagSenderTypeImageDetail
};
typedef NSInteger TagSenderType;
當創建一個通知加入適當枚舉值到您的通知的用戶信息字典@"senderType" : @(TagSenderTypeFeed)
你有沒有考慮使用通知而不是委託? – 2013-03-22 22:49:15