2011-11-22 40 views
8

我想將我的主視圖類中的對象傳遞給另一個類中的其他通知接收器。將對象與NSNotificationCenter傳遞給其他視圖

我想傳遞一個名爲country的對象,它從主控制器中的SOAP請求中加載所有城市,並且我想將它發送到我的下一個視圖。

country = [[Country alloc] init];

國家標頭:

@interface Country : NSObject 
{ 
    NSString *name; 
    NSMutableArray *cities; 
} 

@property (nonatomic,retain) NSString *name; 

- (void)addCity:(Cities *)city; 
- (NSArray *)getCities; 
- (int)citiesCount;  
@end 

我發現了一種方法是使用在一個的UserInfo NSDictionary的傳遞與NSNotificatios數據。但它不可能發送整個對象而不是轉換爲NSDictionary?或者傳輸它的最佳方式是什麼?我堅持試圖找出如何傳遞對象。

其實我在我的應用程序上工作了這個簡單的NSNotification。

NSNotification在主視圖控制器的實現:

//---Call the next View--- 
DetailViewController *detail = [self.storyboardinstantiateViewControllerWithIdentifier:@"Detail"]; 
[self.navigationController pushViewController:detail animated:YES]; 

//--Transfer Data to2View 
[[NSNotificationCenter defaultCenter] postNotificationName:@"citiesListComplete" object:nil]; 

NSNotification在2查看控制器實現:

// Check if MSG is RECEIVE 
- (void)checkMSG:(NSNotification *)note { 

    NSLog(@"Received Notification"); 
} 

- (void)viewDidLoad 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(checkMSG:) 
               name:@"citiesListComplete" object:nil]; 

回答

25

OOOOOO,如此接近。我有一種感覺,你不明白NSDictionary是什麼。

安置自己的這個通知:

Country *country = [[[Country alloc] init] autorelease]; 
//Populate the country object however you want 

NSDictionary *dictionary = [NSDictionary dictionaryWithObject:country forKey:@"Country"]; 

[[NSNotificationCenter defaultCenter] postNotificationName:@"citiesListComplete" object:nil userInfo:dictionary]; 

然後拿到國內的對象是這樣的:

- (void)checkMSG:(NSNotification *)note { 

    Country *country = [[note userInfo] valueForKey:@"Country"]; 

    NSLog(@"Received Notification - Country = %@", country); 
} 

你並不需要將對象轉換爲NSDictionary。相反,你需要發送一個NSDictionary與你的對象。這允許您根據NSDictionary中的密鑰和NSNotification發送大量信息。

+0

謝謝!奇蹟般有效。 我誤解了NSDictionary的概念,但知道它更清楚。 –

+0

謝謝,夥計!我正在使用錯誤的方法,我完全得到通知,但不是userInfo。乾杯。 – Felipe

4

對於斯威夫特 你可以通過字典,使用下面的代碼

NSNotificationCenter.defaultCenter().postNotificationName(aName: String, object anObject: AnyObject?, userInfo aUserInfo: [NSObject : AnyObject]?) 

例如

NSNotificationCenter.defaultCenter().postNotificationName("OrderCancelled", object: nil, userInfo: ["success":true]) 

而且閱讀本字典從

func updated(notification: NSNotification){ 

     notification.userInfo?["success"] as! Bool 
    } 
相關問題