开发者

awakeFromNib and local variable question

Hope I don't get chided for this one...

Can someone explain how this passes the managedObjectContext to the rootViewController?

The following is boilerplate code automatically generated for an iOS core data app:

- (void)awakeFromNib
{
    RootViewController *rootViewController = (RootViewController *)    
    [self.navigationController topViewController];
    rootViewController.managedObjectContext = self.managedObjectContext;
}

In this awakeFromNib, rootViewController is a local variable. Therefore, I thought it would go out of scope when the method ends. I'm betting it has something to do with how the nib is wired in IB, but I'm searching for a better explanation. If I comment out this code, the app crashes because it can't find the obje开发者_运维技巧ct model. I know it works, I would just like to know why and how it works. Thank you!


The variable rootViewController is a pointer to a type RootViewController, and yes it is a local variable. But the object of RootViewController that it points to is not in local-scope. As you can see that you obtain the pointer from the navigationController by asking for it's topViewController. That object is retained by the NavigationController object, so it would still be around even after the pointer goes out of scope. In any case, this is not Java or C# or C++. The objects get deallocated in Objective-C based on reference counting.

You should probably understand more about Memory Management in Objective C to learn more about this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜