2010-10-05 26 views
46

Tôi đang cố gắng gửi một số dữ liệu bằng cách sử dụng NSNotification nhưng bị kẹt. Đây là mã của tôi:Cách chuyển userInfo trong NSNotification?

// Posting Notification 
NSDictionary *orientationData; 
if(iFromInterfaceOrientation == UIInterfaceOrientationLandscapeRight) { 
    orientationData = [NSDictionary dictionaryWithObject:@"Right" 
                forKey:@"Orientation"]; 
} 

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 
[notificationCenter postNotificationName:@"Abhinav" 
            object:nil 
           userInfo:orientationData]; 

// Adding observer 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(orientationChanged) 
              name:@"Abhinav" 
              object:nil]; 

Bây giờ làm thế nào để lấy điển UserInfo này trong selector tôi orientationChanged?

Trả lời

91

Bạn nhận được đối tượng NSNotification được chuyển đến chức năng của bạn. Điều này bao gồm tên, đối tượng và thông tin người dùng mà bạn đã cung cấp cho NSNotificationCenter.

- (void)orientationChanged:(NSNotification *)notification 
{ 
    NSDictionary *dict = [notification userInfo]; 
} 
+0

Ok. Và làm thế nào để làm điều này? Có phải là: [[NSNotificationCenter defaultCenter] addObserver: tự chọn: @selector (orientationChanged: self) tên: @ "Abhinav" đối tượng: nil] ;? – Abhinav

+4

[[NSNotificationCenter defaultCenter] addObserver: tự chọn: @selector (orientationChanged :) tên: @ "Abhinav" đối tượng: nil]; – JustSid

+0

Bất kỳ lý do gì khiến một người có thể kết thúc bằng một từ điển nil? –

23

Bộ chọn của bạn phải có : để chấp nhận tham số.
ví dụ:

@selector(orientationChanged:) 

sau đó trong khai báo phương thức, nó có thể chấp nhận tham số NSNotification.

5

Bạn đang đăng thông báo chính xác. Vui lòng sửa đổi Trình theo dõi thông báo như sau.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) 
name:@"Abhinav" object:nil]; 

- (void)orientationChanged:(NSNotification *)notification 
{ 
    NSDictionary *dict = [notification userInfo]; 
} 

Tôi hy vọng, giải pháp này sẽ làm việc cho bạn ..

0

Trong nhanh chóng Để có được UserInfo đối tượng

 let dict = notification.userInfo 
    print(dict) 
Các vấn đề liên quan