postNotification的观察者被多次调用

时间:2012-05-16 02:24:55

标签: iphone nsnotificationcenter

我正在使用SplitViewController。在MasterViewController的viewDidLoad中:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMasterTable:) name:ReloadMasterTableNotification object:_detailViewController];

在DetailViewController中,我有两个文本字段。在didEndEditing:

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([_detailItem isKindOfClass:[Pill class]]) {
        Pill *p = (Pill *)_detailItem;

        if (textField.tag == TEXTFIELD_NAME_TAG) {
            p.name = textField.text;
        }

        if (textField.tag == TEXTFIELD_NOTE_TAG) {
            p.note = textField.text;
        }

        [self updateMasterTableView];
    }
}


- (void)updateMasterTableView {
    if ([_detailItem isKindOfClass:[Pill class]]) {
        Pill *currentPill = (Pill *)_detailItem;

        NSUInteger indexToReplace = [[[DataManager sharedInstance] pillArray] indexOfObject:currentPill];
        [[[DataManager sharedInstance] pillArray] replaceObjectAtIndex:indexToReplace withObject:currentPill];

        NSLog(@"i should update row: %i", indexToReplace);

        NSIndexPath *path = [NSIndexPath indexPathForRow:indexToReplace inSection:0];
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:path, @"IndexPath", nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:ReloadMasterTableNotification object:self userInfo:dict];
    }
}

从NSLog中,当调用文本字段委托方法时,它只被调用一次,然后updateMasterTableView被调用一次。当我通过调试器运行它,在reloadMasterTableView:方法上放置一个断点时,它会通过该方法两次。这是为什么?感谢。

或者,如果有更好的方法在两个视图之间进行同步,我会全力以赴。

1 个答案:

答案 0 :(得分:0)

我认为实现这一点的更好方法是实现委托模式。

在您的详细控制器.h中定义协议

@protocol PillDetailViewControllerDelegate <NSObject>

- (void)PillDetailViewController:(PillDetailViewController *)vc didUpdatePillAtIndexPath:(NSIndexPath)indexpath;

@end

添加委托属性

@property (nonatomic, assign) id<PillDetailViewControllerDelegate>delegate;

在您的详细控制器中.m,

@synthesize delegate;

而不是在updateMasterTableView中发布您的通知:

[self.delegate PillDetailViewController:self didUpdatePillAtIndexPath:path];

最后在MasterView控制器中,设置委托并响应回调

希望这有帮助

相关问题