编辑:我正在设置准确的365个本地通知UNUserNotification (一年一天一次)。按钮是在同一时间呼叫:
[self name1];
[self name2];
...
[self name365];代码:
-(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注意:每个预定本地通知的标识符是不同的。
发布于 2020-10-25 06:17:22
这并不能直接回答你的问题,你真的应该参数化你的方法,但是我要告诉你的是,你可以帮到很多忙。我想清楚地说明在我的评论中使用#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
https://stackoverflow.com/questions/64507811
复制相似问题