2013-02-21 131 views
2

我有一個父容器視圖控制器的子視圖佔用大部分屏幕的情況。此子視圖用於替換同一數據(地圖,表格和圖庫)的3個不同視圖。有一個分段控件用於選擇用戶想要查看的數據視圖。我在父容器視圖控制器中有一個模型類型的數組集合,我希望這3個不同的子視圖控制器分別在各自的視圖中顯示這些數據。有沒有乾淨的方法來做到這一點,而不必重複數據4次(父母一次,孩子3次)?我假設我將不得不復制數據,因爲孩子不應該能夠調用父視圖控制器來訪問其數組。這也不是一個適當的繼承情況,因爲父級更像是一個容器,而不是相同類型的視圖控制器。這也不是委託的情況,因爲孩子們不需要通知父母任何事情,但相反。如何共享來自容器/父視圖控制器和多個子視圖控制器的數據數組

任何建議非常感謝。

謝謝。

+0

那麼,你必須得到它在某處......在每個子視圖上創建一個屬性?使用類似於UITableView的數據源模式? – onnoweb 2013-02-21 16:56:27

回答

4

我會創建一個類(下面的MyDataController)來管理數據,並使用共享實例從我的應用程序中的任何位置訪問它。

接口(MyDataController.h)

@interface MyDataController : NSObject { 
    NSMutableArray *myData; // this would be the collection that you need to share 
} 
+ (MyDataController*)sharedDataController; 
// ... add functions here to read/write your data 
@end 

實現(MyDataController.m)

static MyDataController* sharedDataController; // this will be unique and contain your data 

@implementation MyDataController 

+ (MyDataController*)sharedDataController 
{ 
    if (!sharedDataController) 
     sharedDataController = [[[MyDataController alloc] init] autorelease]; // no autorelease if ARC 
    return sharedDataController; 
} 

// ... implement your functions to read/write data 
@end 

最後,從任何地方訪問這個靜態對象:

MyDataController *dataController = [MyDataController sharedDataController]; // this will create or return the existing controller; 
+0

謝謝,這是一個很好的方法。 – fogwolf 2013-02-21 21:06:38

0

你可以把單數據類中的數據,並讓每個子視圖控制器從s中獲取數據ingleton。

+0

謝謝,這是我認爲我會做的 - 類似的答案由你之前的人給出。 – fogwolf 2013-02-21 21:07:05

相關問題