如何在Objective-C中的视图控制器之间传递对象?

时间:2010-05-05 03:43:03

标签: iphone objective-c xcode

我一直在跋涉一些代码两天试图找出为什么我无法获取我在.h中声明并在.m中实现并在viewDidLoad函数中设置的全局NSMutableArray变量。

我终于明白了:在Ob​​jective-C中没有全局变量这样的东西,至少在我已经知道的PHP意义上是这样。我从来没有真正阅读过XCode错误警告,但即使不是很简单的英语也是如此:“在类方法中访问实例变量'blah'。”

我的问题:我现在该怎么办?我有两个View Controller需要访问我通过URL从JSON文件生成的中央NSMutableDictionary。它基本上是我所有Table View钻取的扩展菜单,我想要其他几个“全局”(非静态)变量。

每次我想生成这个NSMutableDictionary时,我是否必须获取JSON,或者是否有某种方法可以设置它一次并通过#import从各种类访问它?我是否必须将数据写入文件,或者人们通常会采用其他方式吗?

4 个答案:

答案 0 :(得分:9)

如果你有两个访问共享NSMutableDictionary的视图控制器,你可以将指向公共字典的指针传递到它们各自的初始化消息中吗?

所以在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];
}

答案 1 :(得分:2)

事实上,有很多方法可以做到这一点(不需要采取像写入文件那样极端的东西)。您可以使用以下方法创建“全局”:

  1. 老式C全局变量(外部)
  2. A Singleton
  3. 应用程序委托上的实例变量
  4. 但是所有这些方法都使您的视图控制器不那么模块化(因为它们依赖于到达“外部”来查找全局数据),因此最好的方法可能是使字典成为视图控制器类的属性,必须是由调用者显式设置(在initWithDictionary:方法中,或使用单独的setter)。

答案 2 :(得分:1)

Obj-C中有全局变量,您可以在App Delegate中实例化它们。

但是在您的问题上,您可能希望在实例化新视图控制器时传递NSMutableDictonary,如[UIView alloc] initWithDictionary:(NSMutableDictionary *)dict;如果你明白我的意思。

在你的例子中,你是否有一个类叫另一个类?我认为有某种控制器可以确定要显示哪个视图控制器,这将是访问和传递字典的地方

答案 3 :(得分:1)

只需创建一个全局变量。全球意味着超出任何范围。

NSMutableDictionary *gDictionary;

@implementation ...
@end
相关问题