你绝对可以做得更好,删除委托模式,使用块。
一个基于块的属性添加到您的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