How do you pass objects between View Controllers in Objective-C?

前端 未结 4 1967
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 15:52

I\'ve been trudging through some code for two days trying to figure out why I couldn\'t fetch a global NSMutableArray variable I declared in the .h and implemented in .m and

4条回答
  •  一向
    一向 (楼主)
    2020-12-29 16:26

    If you have two view controllers that access the shared NSMutableDictionary, can you pass a pointer to the common dictionary into their respective init messages?

    So in your 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];
    }
    

    And in your respective UIViewControllerOne and UIViewControllerTwo implementations

    - (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];
    }
    

提交回复
热议问题