objective-c - 创建多个 UILocalNotification

标签 objective-c ios xcode

我想在每次输入某个方法时创建一个新的 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/

相关文章:

iphone - 是重用 View Controller 更好还是分离逻辑更好

objective-c - Xcode - 替换类文件后链接错误 _OBJC_CLASS_$ _"className"

iphone - Xcode4,iOS : Certain parts of instance method being ignored, 没有错误,刚刚过去

ios - Xcode——在 Storyboard中控制+拖动的替代选项,为按钮创建控制转场

objective-c - 嵌套方法调用与一次性变量

ios - 如何防止加载 meteor.local(使用 phonegap 构建 ios 应用程序时)

ios - 正确使用 iPad Pro Assets 目录

iphone - 如何在 UITextField 中显示用户输入的字符之前访问它

iOS 13 强制应用显示蓝牙权限提示

ios - 注册大量 UICollectionViewCell 类以在 UICollectionView 中重用