Reputation: 3172
In my project, I am planning to use NSNotificationCenter
for class-to-class communication. Therefore I am going to add a lot of observers in NSNotificationCenter
. I am wondering if this is safe? or in other words, is this a good practice? Actually I am refactoring my code right now, and I want to sort out methods that shouldn't be done inside a class. As a matter of fact, I have a lot of alert controllers inside a UIViewController
and it really bothers me every time I am debugging. Now, I just took out all those alert controllers and wrapped them in another class. For the callback block in UIAlertAction
I am sending a notification to the UIViewController
. Thats is why I am adding a lot of observers. Any suggestions would be appreciated. Thank you very much!
Upvotes: 0
Views: 55
Reputation: 7552
There is nothing wrong, per se, with multiple observers for the same notification, or for a class to observe multiple notifications.
On the specific question of using notifications to pass information regarding UIAlertActions, don't do that. There's nothing wrong with having a class that hides the boilerplate of creating specific UIAlertViewController instances with specific actions. However, the API for such a class should have factory methods for each specific alert, and those methods should take blocks as parameters to represent the action handlers. The bodies of the blocks would be defined in the UIViewController that invokes the alert.
Example
@interface CustomAlertsFactory : NSObject
+ (void)presentDeleteConfirmationAlertFromViewController:(UIViewController *)viewController
withConfirmAction:(void (^)(UIAlertAction *action))confirmHandler
cancelAction:(void (^)(UIAlertAction *action))cancelHandler;
@end
The implementation of that method would create a UIAlertViewController tailored as a delete confirmation. The confirm and cancel actions would be configured to use the blocks passed as parameters.
On the view controller side, imagine you allow editing a table. In tableView:commitEditingStyle:forRowAtIndexPath:
you would throw up the alert as follows:
[CustomAlertsFactory
presentDeleteConfirmationAlertFromViewController:self
withConfirmationAction:^(UIAlertAction *a) {
[tableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self dismissViewControllerAnimated:YES completion:NULL];
}
cancelAction:^(UIAlertAction *a) {
[self dismissViewControllerAnimated:YES completion:NULL];
}
];
Upvotes: 1