IT

NSNotificationCenter로 객체를 전달하는 방법

lottoking 2020. 7. 11. 09:19
반응형

NSNotificationCenter로 객체를 전달하는 방법


내 앱 대리자에서 다른 클래스의 알림 전달을 전달합니다.

정수 전달하고 싶습니다 messageTotal. 지금 나는 가지고 있습니다 :

여기에서 :

- (void) receiveTestNotification:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"TestNotification"])
        NSLog (@"Successfully received the test notification!");
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissSheet) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@"eRXReceived" object:nil];

알림을 수행하는 클래스에서 :

[UIApplication sharedApplication].applicationIconBadgeNumber = messageTotal;
[[NSNotificationCenter defaultCenter] postNotificationName:@"eRXReceived" object:self];

object- 그러나 messageTotal를 다른 클래스 에 전달하고 싶습니다 .


"userInfo"를 변경하고 messageTotal 정수를 전달해야합니다.

NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

수신 측에서 다음과 같이 userInfo 사전에 액세스 할 수 있습니다.

-(void) receiveTestNotification:(NSNotification*)notification
{
    if ([notification.name isEqualToString:@"TestNotification"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSNumber* total = (NSNumber*)userInfo[@"total"];
        NSLog (@"Successfully received test notification! %i", total.intValue);
    }
}

솔루션 솔루션을 기반으로 정의 데이터 객체에서 (여기서는 질문 당 '거기에서'로 참조)를 전달하는 예제를 전달하는 것이 도움이 생각했습니다.

클래스 A (발신자) :

YourDataObject *message = [[YourDataObject alloc] init];
// set your message properties
NSDictionary *dict = [NSDictionary dictionaryWithObject:message forKey:@"message"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:nil userInfo:dict];

클래스 B (수신자) :

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(triggerAction:) name:@"NotificationMessageEvent" object:nil];
}

#pragma mark - Notification
-(void) triggerAction:(NSNotification *) notification
{
    NSDictionary *dict = notification.userInfo;
    YourDataObject *message = [dict valueForKey:@"message"];
    if (message != nil) {
        // do stuff here with your message data
    }
}


스위프트 2 버전

@Johan Karlsson이 지적했듯이 ... 나는 그것을 잘못하고 있었다. NSNotificationCenter를 사용하여 정보를 보내는 적절한 방법은 다음과 가변합니다.

먼저 postNotificationName의 이니셜 라이저를 살펴 봅니다.

init(name name: String,
   object object: AnyObject?,
 userInfo userInfo: [NSObject : AnyObject]?)

출처

userInfoparam을 사용하여 정보를 많은 것 입니다. [NSObject : AnyObject]유형은 Objective-C 의 보류 입니다. 따라서 Swift 땅에서 우리가해야 할 일 키에서 파생 된 키 NSObject와 값이 될 수 있는 Swift 사전을 전달 하는 것 AnyObject입니다.

그 지식으로 object매개 변수에 사전을 만듭니다 .

 var userInfo = [String:String]()
 userInfo["UserName"] = "Dan"
 userInfo["Something"] = "Could be any object including a custom Type."

그런 다음 사전을 전달하는 변수에 전달합니다.

위 사람

NSNotificationCenter.defaultCenter()
    .postNotificationName("myCustomId", object: nil, userInfo: userInfo)

서비스 클래스

클래스가 알림을 관찰하는지 먼저 확인해야합니다.

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("btnClicked:"), name: "myCustomId", object: nil)   
}

그런 다음 사전을받을 수 있습니다.

func btnClicked(notification: NSNotification) {
   let userInfo : [String:String!] = notification.userInfo as! [String:String!]
   let name = userInfo["UserName"]
   print(name)
}

스위프트 5

func post() {
    NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"), 
        object: nil, 
        userInfo:["key0": "value", "key1": 1234])
}

func addObservers() {
    NotificationCenter.default.addObserver(self, 
        selector: #selector(someMethod), 
        name: Notification.Name("SomeNotificationName"), 
        object: nil)
}

@objc func someMethod(_ notification: Notification) {
    let info0 = notification.userInfo?["key0"]
    let info1 = notification.userInfo?["key1"]
}

보너스 (당연히해야합니다!) :

교체 Notification.Name("SomeNotificationName").someNotificationName:

extension Notification.Name {
    static let someNotificationName = Notification.Name("SomeNotificationName")
}

교체 "key0""key1"함께 Notification.Key.key0Notification.Key.key1:

extension Notification {
  enum Key: String {
    case key0
    case key1
  }
}

왜 내가해야 할 필요가 있습니까? 값 비싼 오타 오류를 방지 비용 이름 변경, 사용법 찾기 등을 즐기십시오.

참고 URL : https://stackoverflow.com/questions/7896646/how-to-pass-object-with-nsnotificationcenter

반응형