[self name1];
[self name2];
...
[self name365];
- 每天一个名字。如果我只试三天,效果很好。如果我整天打电话(365x(,它只会触发最后一个本地通知(365。仅(-第1-364天未命中(未被解雇(。有什么想法吗
代码:
-(void)Name1{
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.hour = 9;
comps.minute = 0;
comps.day = 23;
comps.month = 10;
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@"NAME" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"text"
arguments:nil];
objNotificationContent.sound = [UNNotificationSound soundNamed:@"notif_bobicek.mp3"];
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents: comps repeats:YES];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"requestNotificationForName1"
content:objNotificationContent trigger:trigger];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) { NSLog(@"Local Notification succeeded"); }
else { NSLog(@"Local Notification failed"); }}];
}
-(void)Name2{ ... // same code
-(void)Name365{... // same code
注意:每个计划的本地通知的标识符不同。
这并不能直接回答您的问题,您确实应该将您的方法参数化,但我将向您展示的内容可以帮助您。我想清楚地说明我在评论中使用#define的意思。
使用#define是解决一些棘手问题的强大方法,即使在这里,它也可以让你的生活变得更轻松。把#define想象成一种搜索和替换类型,它过去确实是这样,在这里你可以用它来定义你的消息一次,然后替换365次,而不是创建365条不同的消息。这是一个大纲。
// MyClass.m
#import "MyClass.h"
// The indicates the macro continues on the next line
// Note this becomes just one long string without linebreaks so you can
// not use // to comment, you must use /* ... */ to comment
// The ## indicates it is a string concatenation
#define MYFUNC( DAY )
- ( void ) name ## DAY {
/* Now you are inside nameDAY e.g. name1, name2 ... etc */
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.hour = 9;
comps.minute = 0;
comps.day = 23;
comps.month = 10;
/* Some examples below */
NSUInteger day = DAY;
NSString * s = [NSString stringWithFormat:@"ID:%lu", DAY];
NSLog( @"Inside %@", s );
};
@implementation MyClass
// Now you can create them as below
MYFUNC( 1 )
MYFUNC( 2 )
MYFUNC( 3 )
MYFUNC( 4 )
// etc
// They are now defined and can be called as normal
- ( void ) test
{
[self name1];
[self name2];
[self name3];
// etc
}
@end
如果您将方法参数化,但仍需要365个函数,则可以通过添加更多参数来扩展#define。无论如何,要了解更多信息,请参阅这个非常好的参考资料。
https://en.wikibooks.org/wiki/C_Programming/Preprocessor_directives_and_macros
HIH-