我正在嘗試將通知從一個班級發送到另一個班級,但從notificationReceived未被呼叫。
應用委托:
#import <Cocoa/Cocoa.h>
#import "TestManager.h"
@interface AppDelegate : NSObject <NSApplicationDelegate>
@end
------------------------------
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSLog(@"did finish launching");
[[TestManager alloc] init];
}
@end
經理:
#import <AppKit/AppKit.h>
#import "TestObserver.h"
@interface TestManager : NSObject
@end
------------------------------
#import "TestManager.h"
@implementation TestManager
- (instancetype)init {
self = [super init];
if (self) {
NSLog(@"manager init");
[[TestObserver alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationReceived) name:@"testnotification" object:nil];
}
return self;
}
- (void)notificationReceived {
NSLog(@"notification received");
}
@end
觀察員:
#import <AppKit/AppKit.h>
@interface TestObserver : NSObject
@end
------------------------------
#import "TestObserver.h"
@implementation TestObserver
- (instancetype)init {
self = [super init];
if (self) {
NSLog(@"observer init");
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendNotification) userInfo:nil repeats:YES];
}
return self;
}
- (void)sendNotification {
NSLog(@"observer post");
[[NSNotificationCenter defaultCenter] postNotificationName:@"testnotification" object:nil];
}
@end
uj5u.com熱心網友回復:
兩者TestManager和都TestObserver必須是屬性/ivar,否則任何一個都被過早地釋放。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/513004.html
標籤:目标-c苹果系统nsnotificationcenter
