I am maintaining an old iOS project which based on SDK 6.0.
A method on this project called
-(void) showComboBox:(UIView*)view:withOptions:(NSDictiona
While it may look very simple, there is a nasty issue with using UIAlertController. It is memory leaks prone. In order to test if you have the issue, just put a breakpoint at your view controller's dealloc method and see if it's deallocated properly.
I was looking for a solution for quite some time and here is how I use an alert controller in my app.
+ (void)alertWithPresenting:(UIViewController *)presenting title:(NSString *)title
text:(NSString *)text buttons:(NSArray *)buttons
handler:(void (^)(UIAlertAction *action, NSUInteger index))handler
{
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:title message:text
preferredStyle:UIAlertControllerStyleAlert];
__weak __typeof(alert) weakAlert = alert;
for (NSString *title in buttons) {
UIAlertActionStyle style = UIAlertActionStyleDefault;
if ([title isEqualToString:[L10n cancelButton]])
style = UIAlertActionStyleCancel;
else if ([title isEqualToString:[L10n deleteButton]])
style = UIAlertActionStyleDestructive;
else if ([title isEqualToString:[L10n archiveButton]])
style = UIAlertActionStyleDestructive;
UIAlertAction *action = [UIAlertAction actionWithTitle:title style:style handler:^(UIAlertAction *action) {
if (handler != nil)
handler(action, [buttons indexOfObject:action.title]);
[weakAlert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:action];
}
[presenting presentViewController:alert animated:YES completion:nil];
}
This is not all. Here is an example of how you use it in your view controller. In my case its tableview with search, so presenting controller may be different.
- (void) deleteCases:(NSArray *)selectedRows
{
NSString *text = NSLocalizedStringWithDefaultValue(@"cases.delete.alert.text",
@"Localizable", [NSBundle mainBundle],
@"Deleted cases cannot be restored. Continue with delete?",
@"Delete alert text");
NSString *title = NSLocalizedStringWithDefaultValue(@"cases.delete.alert.title",
@"Localizable", [NSBundle mainBundle],
@"Delete cases", @"Detete alert title");
UIViewController *presenting = self.searchController.active ? self.searchController : self;
__weak __typeof(presenting) weakPresenting = presenting;
__weak __typeof(self) weakSelf = self;
[YourClassName alertWithPresenting:weakPresenting title:title text:text
buttons:@[[L10n deleteButton], [L10n cancelButton]]
handler:^(UIAlertAction *action, NSUInteger index)
{
if (action.style == UIAlertActionStyleDestructive) {
__typeof(weakSelf) strongSelf = weakSelf;
// Perform your actions using @strongSelf
}
}];
}