I’m trying to load a new view into an existing view controller, but I want to load that view from a xib file. My plan was to create a second viewController (viewController1 in the code below), then retain its view and release that viewController that I just created. I was hoping that the viewController would be released and the view would stick around, but that doesn’t seem to be happening.
Question 1: If a viewcontroller gets dealloced, does its associated view get dealloced no matter what the view’s retain count is? In my sample code below, you can see that the view has a retain count of 13 before it suddenly just disappears.
Question 2: Why does retaining the view increase its retainCount by 3?
PageViewController *viewController1 = [[PageViewController alloc] initWithNibName:@"Page1" bundle:nil];
[viewController1.view setUserInteractionEnabled:YES];
NSLog (@"vc retain count: %d", [viewController1 retainCount]); //count=1
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); //count=4
self.currentPageView=viewController1.view;
NSLog (@"vc retain count: %d", [viewController1 retainCount]); //count=1
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); //count=7
[viewController1.view retain];
NSLog (@"vc retain count: %d", [viewController1 retainCount]); //count=1
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); //count=10
[self.view addSubview:viewController1.view];
NSLog (@"vc retain count: %d", [viewController1 retainCount]); //count=1
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); //count=13
[viewController1 release];
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]);
//objc[3237]: FREED(id): message view sent to freed object=0x538ce0
The error you’re getting about the “message sent to freed object” isn’t telling you that the view has been freed, it’s that
viewController1has been freed, and thus you’re getting an error when you send it the “view” message. (remember that in Objective C every property access really sends a message…)I’m not sure why the view’s retain count is jumping up by 3 each time, though.