![](/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.