问题描述
我正在设置365个本地通知(每年每天一次)。按钮一次通话:
[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
解决方法
这不能直接回答您的问题,您确实应该参数化您的方法,但是我将向您展示的内容会有所帮助。我想清楚地说明我在评论中使用#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