为 NSNotificationCenter 添加乘法观察者

Adding Multiply Observers For NSNotificationCenter

在我的项目中,我计划使用 NSNotificationCenter 进行 class 到 class 的通信。因此,我将在 NSNotificationCenter 中添加很多观察者。我想知道这是否安全?或者换句话说,这是一个好的做法吗?其实我现在正在重构我的代码,我想把不应该在class里面做的方法整理出来。事实上,我在 UIViewController 中有很多警报控制器,每次调试时它真的很困扰我。现在,我只是取出所有那些警报控制器并将它们包裹在另一个 class 中。对于 UIAlertAction 中的回调块,我正在向 UIViewController 发送通知。这就是我添加大量观察员的原因。任何建议,将不胜感激。非常感谢!

从本质上讲,对于同一个通知有多个观察者,或者 class 观察多个通知,这并没有错。

关于使用通知传递有关 UIAlertActions 的信息的具体问题,请不要这样做。使用 class 隐藏创建具有特定操作的特定 UIAlertViewController 实例的样板并没有错。但是,class 的 API 应该有针对每个特定警报的工厂方法,并且这些方法应该将块作为参数来表示操作处理程序。块的主体将在调用警报的 UIViewController 中定义。

例子

@interface CustomAlertsFactory : NSObject

+ (void)presentDeleteConfirmationAlertFromViewController:(UIViewController *)viewController
                                       withConfirmAction:(void (^)(UIAlertAction *action))confirmHandler
                                            cancelAction:(void (^)(UIAlertAction *action))cancelHandler;

@end

该方法的实现将创建一个定制为删除确认的 UIAlertViewController。确认和取消操作将配置为使用作为参数传递的块。

在视图控制器端,假设您允许编辑 table。在 tableView:commitEditingStyle:forRowAtIndexPath: 中,您将按如下方式抛出警报:

[CustomAlertsFactory
 presentDeleteConfirmationAlertFromViewController:self
 withConfirmationAction:^(UIAlertAction *a) {
    [tableView deleteRowsAtIndexPaths:@[indexPath]
                     withRowAnimation:UITableViewRowAnimationFade];

    [self dismissViewControllerAnimated:YES completion:NULL];
 }
 cancelAction:^(UIAlertAction *a) {
    [self dismissViewControllerAnimated:YES completion:NULL];
 }
];