我想在每次输入某个方法时创建一个新的 UILocalNotification。我认为这必须通过读取数组或类似的东西来完成,但我无法弄清楚。我如何动态地做这样的事情而不需要硬编码如下:
-(void) createNotification
{
UILocalNotification *notification1;
}
现在我希望每次输入 createNotification 时都能创建 notification2、notification3 等。由于具体原因,我可以取消相应的通知,而无需全部取消。
以下是我尝试过的,也许还很遥远......也许不是。无论哪种方式,如果有人可以提供一些意见,我们将不胜感激。谢谢!
-(void) AddNewNotification
{
UILocalNotification *newNotification = [[UILocalNotification alloc] init];
//[notificationArray addObject:newNotification withKey:@"notificationN"];
notificationArray= [[NSMutableArray alloc] init];
[notificationArray addObject:[[NSMutableDictionary alloc]
initWithObjectsAndKeys:newNotification,@"theNotification",nil]];
}
最佳答案
您已经快完成了:使用数组无疑是正确的做法!唯一的问题是,每次执行 AddNewNotification
方法时,您都会不断创建数组的新实例。您应该将 notificationArray
设为实例变量,并将其初始化代码 notificationArray= [[NSMutableArray alloc] init];
移动到 notificationArray< 所在类的指定初始值设定项
已声明。
如果您想在每次插入一个单独的键时发出通知,以便稍后可以找到它,请使用 NSMutableDictionary
而不是 NSMutableArray
。重写 AddNewNotification
方法,如下所示:
-(void) addNewNotificationWithKey:(NSString*)key {
UILocalNotification *newNotification = [[UILocalNotification alloc] init];
[notificationDict setObject:[[NSMutableDictionary alloc]
initWithObjectsAndKeys:newNotification,@"theNotification",nil]
forKey:key];
}
例如,当您调用 addNewNotificationWithKey:
方法时,您可以为新添加的通知提供 key
[self addNewNotificationWithKey:@"notification1"];
[self addNewNotificationWithKey:@"notification2"];
等等。
关于objective-c - 创建多个 UILocalNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11387650/