[ios] Objective-C에서 NSNotificationCenter를 통해 메시지를주고 받습니까?
NSNotificationCenter
Objective-C를 통해 메시지를 보내고 받으려고합니다 . 그러나이 작업을 수행하는 방법에 대한 예를 찾지 못했습니다. 메시지를 NSNotificationCenter
어떻게 주고 받 습니까?
답변
@implementation TestClass
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (id) init
{
self = [super init];
if (!self) return nil;
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
return self;
}
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
@end
… 다른 수업 어딘가에 …
- (void) someMethod
{
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TestNotification"
object:self];
}
답변
dreamlax의 예 를 확장하려면 … 알림과 함께 데이터를 보내려면
게시 코드에서 :
NSDictionary *userInfo =
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName:
@"TestNotification" object:nil userInfo:userInfo];
코드를 관찰 할 때 :
- (void) receiveTestNotification:(NSNotification *) notification {
NSDictionary *userInfo = notification.userInfo;
MyObject *myObject = [userInfo objectForKey:@"someKey"];
}
답변
이것은 나를 도왔다 :
// Add an observer that will respond to loginComplete
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(showMainMenu:)
name:@"loginComplete" object:nil];
// Post a notification to loginComplete
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginComplete" object:nil];
// the function specified in the same class where we defined the addObserver
- (void)showMainMenu:(NSNotification *)note {
NSLog(@"Received Notification - Someone seems to have logged in");
}
출처:
http://www.smipple.net/snippet/Sounden/Simple%20NSNotificationCenter%20example
답변
블록을 사용할 가능성도 있습니다 :
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter]
addObserverForName:@"notificationName"
object:nil
queue:mainQueue
usingBlock:^(NSNotification *notification)
{
NSLog(@"Notification received!");
NSDictionary *userInfo = notification.userInfo;
// ...
}];
답변
NSNotificationCenter를 사용하여 뷰를 업데이트하는 경우 다음을 호출하여 메인 스레드에서 뷰를 보내는 것을 잊지 마십시오 dispatch_async
.
dispatch_async(dispatch_get_main_queue(),^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});
답변
초보자를위한 선별 된 답변의 SWIFT 5.1
class TestClass {
deinit {
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
NotificationCenter.default.removeObserver(self)
}
init() {
super.init()
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
}
@objc func receiveTest(_ notification: Notification?) {
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if notification?.name.isEqual(toString: "TestNotification") != nil {
print("Successfully received the test notification!")
}
}
}
… 다른 수업 어딘가에 …
func someMethod(){
// All instances of TestClass will be notified
NotificationCenter.default.post(name: "TestNotification", object: self)
}