Reputation: 11728
Here is the scenario: In my app I'm syncing some data, whenever there is some error when syncing I flag this in a BOOL
. When all syncing is complete I want to display sync feedback (errors) for the user.
If there is ie a calendar sync error and a contact sync error I first display a UIAlertView
with information about the calendar sync error, when the user has tapped "OK" I then display a UIAlertView
with information about the contact sync error. To be able to know when the user has tapped "OK" I use completion blocks. So my code looks something like this:
if (calendarSyncFailed && contactSyncFailed && facebookSyncFailed && contactSyncConflicts) {
[self displayCalendarSyncAlertCompletionBlock:^{
[self displayContactsSyncAlertCompletionBlock:^{
[self displayFacebookSyncAlertCompletionBlock:^{
[self displayContactSyncConflictsAlertCompletionBlock:^{
}];
}];
}];
}];
} else if (calendarSyncFailed && contactSyncFailed && facebookSyncFailed) {
[self displayCalendarSyncAlertCompletionBlock:^{
[self displayContactsSyncAlertCompletionBlock:^{
[self displayFacebookSyncAlertCompletionBlock:^{
}];
}];
}];
} else if (contactSyncFailed && facebookSyncFailed && contactSyncConflicts) {
[self displayContactsSyncAlertCompletionBlock:^{
[self displayFacebookSyncAlertCompletionBlock:^{
[self displayContactSyncConflictsAlertCompletionBlock:^{
}];
}];
}];
} else if (you get the idea…) {
}
As you can see there will be alot of different combinations for dealing with these 4 boolean values and I was wondering if there is a more smarter/elegant way of coding this?
Upvotes: 2
Views: 163
Reputation: 989
While I do agree with demosten that it would be better to have only one message, this is how I would do this with less code:
Use a mutable array as a property where you store your alertviews.
In the method where you test your conditions, create an alert view for every failure that evaluates to true, and put them in your array in the desired order. (This is the key part as you are only doing 4 tests, instead of 2^4 - 1 tests).
Implement the UIAlertViewDelegate
method alertView: didDismissWithButtonIndex:
something like this:
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSInteger nextIndex = [self.alertViews indexOfObject:alertView] + 1;
if (nextIndex < [self.alertViews count]){
UIAlertView *next = [self.alertViews objectAtIndex: nextIndex];
[next show];
}
}
Upvotes: 2