我花了两天时间艰难地研究一些代码,试图找出为什么我无法获取我在 .h 中声明并在 .m 中实现并在 viewDidLoad 函数中设置的全局 NSMutableArray 变量。
我终于明白了:Objective-C 中不存在全局变量这样的东西,至少在我所了解的 PHP 意义上是这样。我没有真正读过 XCode 错误警告,但它就在那里,即使不是很简单的英语:“实例变量‘blah’在类方法中访问。”
我的问题:我现在应该做什么?我有两个视图控制器,需要访问我通过 URL 从 JSON 文件生成的中央 NSMutableDictionary。它基本上是我所有表视图钻取的扩展菜单,我想要一些其他“全局”(非静态)变量。
每次我想要生成此 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];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)