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

bul*_*ley 5 iphone xcode objective-c

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

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

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

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

Red*_*ing 9

如果您有两个访问共享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];
}
Run Code Online (Sandbox Code Playgroud)

并在各自的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];
}
Run Code Online (Sandbox Code Playgroud)