2013-06-24 66 views
0

我有一個表格視圖控制器,應該填充來自封裝在store類中的數組的數據。該表需要通過方法table:numberOfRowsInSection:知道每個部分中有多少行。在這種方法中,我需要返回store實例中的數組大小。我最初是通過將store作爲singleton來做到這一點的,但被告知這樣做效率低下,使用NSNotificationCenter會更好。如何使用NSNotificationCenter傳輸數據ViewControllers/classes?

據我所知,所有NSNotificationCenter所做的是在另一個對象發佈特定通知時在特定對象中觸發方法。我如何使用NSNotificationCenter將數組的大小發送到我的表視圖控制器?

+0

沒有關於數據的信息很難確定,但'NSNotificationCenter'或單例都不是很好的模式。爲什麼不只是添加一個屬性到你的表視圖控制器,指向'store'?你能談談更多關於數據的內容嗎? – MaxGabriel

+0

通過通知發送行數不是一個好主意。通知,顧名思義,應該只用於通知。在你的情況下,它應該用來通知商店發生了一些變化。然後從商店實例中檢索實際數據(例如行數,部分等)(無論是單例還是視圖控制器參考的實例)。 –

+0

我有一個表視圖控制器,需要填充滿的字符串數組。該數組是另一個類「Store」的屬性。我應該在我的表視圖控制器的啓動中創建此存儲並給表視圖控制器參考它嗎? –

回答

2

你可以這樣說:

... 
// Send 
[[NSNotificationCenter defaultCenter] postNotificationName: SizeOfRrrayNotification 
                object: [NSNumber numberWithInteger: [array count]]]; 

... 
// Subscribe 
[[NSNotificationCenter defaultCenter] addObserver: self 
             selector: @selector(sizeOfArray:) 
              name: SizeOfRrrayNotification 
              object: nil]; 

// Get size 
- (void) sizeOfArray: (NSNotification*) notification 
{ 
    NSNumber* sizeOfArray = (NSNumber*) notification.object; 
    NSLog(@"size of array=%i", [sizeOfArray integerValue]); 
} 
+0

添加觀察者時,請記得刪除觀察者以及... – lakesh

0

郵政通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyArraySize" object: [NSNumber numberWithInteger: [myArray count]]] userInfo:nil]; 

得到通知:

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

添加這種方法在v iewController你在哪裏得到通知:

- (void) getSizeOfArray: (NSNotification*) notification 
{ 
    NSNumber* myArraySize = (NSNumber*) notification.object; 
} 

,你甚至可以通過「userInfo」發送更多的數據,並使用notification.userInfo獲得選擇方法的數據,但要記住它的類型是「NSDictionary

希望這會幫助你。

0

的方法,要在其中計算所述陣列的大小:

< ------通知發送側---------->

-(void)sizeOfArray{ 
    int size = [myArray count]; 
    NSMutableString *myString = [NSMutable string]; 
    NSString *str = [NSString stringwithFormat:@"%d",size]; 
    [myString apprndString:str]; 

//It is to be noted that NSNotification always uses NSobject hence the creation of mystring,instead of just passing size 

    [[NSNotificationCenter defaultCenter] postNotificationName:@"GetSizeOfArray"  object:myString]; 
} 

現在一旦你已經發布了通知,其中,要發送的數據

<此添加到控制器的viewDidLoad方法------通知接收側---------->

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

//The selector method should always have a notification object as its argument 

[super viewDidLoad]; 

} 


- (void)get_notified:(NSNotification *)notif { 
    //This method has notification object in its argument 

    if([[notif name] isEqualToString:@"GetSizeOfArray"]){ 
     NSString *temp = [notif object]; 
     int size = [temp int value]; 

     //Data is passed. 
     [self.tableView reloadData]; //If its necessary 

    }  
} 

希望這會有所幫助。

相關問題