我正在开发一个系统来跟踪成就并为此使用NSNotificationCenter
. 当应用程序中的对象解锁成就时,会发送通知JMAchievementHandler
,将字符串设置为YES
并将进度保存在NSUserDefaults
. 我的问题是通知可能不起作用。这是我的代码JMAchievementHandler
:
- (id)init {
self = [super init];
if (self) {
//Set strings to NO
achievementOne = @"NO";
achievementTwo = @"NO";
achievementThree = @"NO";
achievementFour = @"NO";
//Add observers
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationWithName:) name:@"achievement1" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationWithName) name:@"achievement2" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationWithName) name:@"achievement3" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationWithName) name:@"achievement4" object:nil];
//Add observer to observe delegate methods
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationFromDelegate:) name:@"notificationLaunch" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationFromDelegate:) name:@"notificationEnterBackground" object:nil];
}
return self;
}
- (void)receiveNotificationWithName:(NSNotification *)notification {
if ([[notification name] isEqualToString:@"achievement1"] || [achievementOne isEqualToString:@"NO"]) {
//unlock achievement
NSLog(@"%@ is unlocked", [notification name]);
achievementOne = @"YES";
}
else if ([[notification name] isEqualToString:@"achievement2"] || [achievementTwo isEqualToString:@"NO"]) {
//unlock achievement
NSLog(@"%@ is unlocked", [notification name]);
achievementTwo = @"YES";
}
else if ([[notification name] isEqualToString:@"achievement3"] || [achievementThree isEqualToString:@"NO"]) {
//unlock achievement
NSLog(@"%@ is unlocked", [notification name]);
achievementThree = @"YES";
}
else if ([[notification name] isEqualToString:@"achievement4"] || [achievementFour isEqualToString:@"NO"]) {
//unlock achievement
NSLog(@"%@ is unlocked", [notification name]);
achievementFour = @"YES";
}
}
- (void)receiveNotificationFromDelegate:(NSNotification *)notificationDelegate
{
if ([[notificationDelegate name] isEqualToString:@"notificationLaunch"]) {
[self loadDataOnLaunch];
}
else if ([[notificationDelegate name] isEqualToString:@"notificationEnterBackground"]) {
[self saveDataOnExit];
}
}
- (void)loadDataOnLaunch
{
NSLog(@"loadDataOnLaunch");
}
- (void)saveDataOnExit
{
NSLog(@"saveDataOnExit");
}
当我尝试发布通知时,不会调用 NSLog。我使用以下代码从我的AppDelegate
和发送通知ViewController
。
- (void)achievement1ButtonPressed:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"achievement1" object:self userInfo:nil];
}
我希望你们能帮助我。非常感谢
- 乔纳斯