The answer to your problem lies in the userInfo
dictionary parameter that every UILocalNotification
has. You can set values for keys in this dictionary to identify the notification.
To implement this easily all you have to do is have your timer class have an NSString
"name" property. And use some class wide string for the key for that value. Here is a basic example based on your code:
#define kTimerNameKey @"kTimerNameKey"
-(void)cancelAlarm{
for (UILocalNotification *notification in [[[UIApplication sharedApplication] scheduledLocalNotifications] copy]){
NSDictionary *userInfo = notification.userInfo;
if ([self.name isEqualToString:[userInfo objectForKey:kTimerNameKey]]){
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
}
-(void)scheduleAlarm{
[self cancelAlarm]; //clear any previous alarms
UILocalNotification *alarm = [[UILocalNotification alloc] init];
alarm.alertBody = @"alert msg";
alarm.fireDate = [NSDate dateWithTimeInterval:alarmDuration sinceDate:startTime];
alarm.soundName = UILocalNotificationDefaultSoundName;
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:self.name forKey:kTimerNameKey];
alarm.userInfo = userInfo;
[[UIApplication sharedApplication] scheduleLocalNotification:alarm];
}
This implementation should be relatively self explanatory. Basically when an instance of the timer class has -scheduleAlarm
called and it is creating a new notification it sets it's string property "name" as the value for the kTimerNameKey
. So when this instance calls -cancelAlarm
it enumerates the array of notifications looking for a notification with it's name for that key. And if it finds one it removes it.
I imagine your next question will be how to give each of your timers name property a unique string. Since I happen to know you are using IB to instantiate them (from your other question on the matter) you would likely do this in viewDidLoad
something like:
self.timerA.name = @"timerA";
self.timerB.name = @"timerB";
You could also tie the name property in with a title label you may have.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…