![](/img/trans.png)
[英]How do I share common methods between view controllers in Objective-C?
[英]How do you pass objects between View Controllers in Objective-C?
我已經跋涉了兩天的代碼試圖找出為什么我無法獲取我在.h中聲明並在.m中實現並在viewDidLoad函數中設置的全局NSMutableArray變量。
它終於明白了:在Objective-C中沒有全局變量這樣的東西,至少在我已經知道的PHP意義上是這樣。 我從來沒有真正閱讀過XCode錯誤警告,但即使不是很簡單的英語也是如此:“在類方法中訪問實例變量'blah'。”
我的問題:我現在該怎么辦? 我有兩個View Controller需要訪問我通過URL從JSON文件生成的中央NSMutableDictionary。 它基本上是我所有Table View鑽取的擴展菜單,我想要其他幾個“全局”(非靜態)變量。
每次我想生成這個NSMutableDictionary時,我是否必須獲取JSON,或者是否有某種方法可以設置它一次並通過#import從各種類訪問它? 我是否必須將數據寫入文件,還是人們通常會采用其他方式?
如果您有兩個訪問共享NSMutableDictionary的視圖控制器,您是否可以將指向公共字典的指針傳遞到它們各自的init消息中?
所以在你的AppDelegate中:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// the app delegate doesn't keep a reference this, it just passes it to the
// view controllers who retain the data (and it goes away when both have been released)
NSMutableDictionary * commonData = [[NSMutableDictionary new] autorelease];
// some method to parse the JSON and build the dictionary
[self populateDataFromJSON:commonData];
// each view controller retains the pointer to NSMutableDictionary (and releases it on dealloc)
self.m_viewControllerOne = [[[UIViewControllerOne alloc] initWithData:commonData] autorelease];
self.m_viewControllerTwo = [[[UIViewControllerTwo alloc] initWithData:commonData] autorelease];
}
並在各自的UIViewControllerOne和UIViewControllerTwo實現中
- (id)initWithData:(NSMutableDictionary*)data
{
// call the base class ini
if (!(self=[super init]))
return nil;
// set your retained property
self.sharedData = data;
}
// don't forget to release the property
- (void)dealloc {
[sharedData release];
[super dealloc];
}
事實上,有很多方法可以做到這一點(沒有采取像寫入文件那樣極端的事情)。 您可以使用以下命令創建“全局”:
但是所有這些方法都使得視圖控制器不那么模塊化(因為它們依賴於到達“外部”來查找全局數據),因此最好的方法可能是使字典成為必須由顯式設置的視圖控制器類的屬性。調用者(在initWithDictionary:方法中,或使用單獨的setter)。
Obj-C中有全局變量,您可以在App Delegate中實例化它們。
但是在您的問題上,您可能希望在實例化新視圖控制器時傳遞NSMutableDictonary,如[UIView alloc] initWithDictionary:(NSMutableDictionary *)dict; 如果你明白我的意思。
在你的例子中,你有一個類叫另一個類嗎? 我認為有某種控制器可以確定要顯示哪個視圖控制器,這將是訪問和傳遞字典的地方
只需創建一個全局變量。 全球意味着超出任何范圍。
NSMutableDictionary *gDictionary;
@implementation ...
@end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.