Crasher in a custom view as UINavigationController

2019-08-29 23:30发布

问题:

I have an UIViewController with several subviews in its view property (UISearchbar and several UIButtons). The UIButtons hooked up to typical IBActions like -(IBAction)buttonPressed:(id)sender for the UIControlEventTouchUpInside state - it doesn't matter if I do it in IB or programmatically.

- (void)viewDidLoad {
    MUZTitleViewController *title = [[MUZTitleViewController alloc] 
                                     initWithNibName:nil bundle:nil];
    self.navigationItem.titleView = title.view;
}

In my project there's also an UINavigationController. When I set the navigationItem.titleView of the UINavigationBar to the view of my UIViewControllers view I get an EXC_BAD_ACCESS exception, as soon as I tap one of the button. I don't know why this is.

I uploaded a small sample project to illustrate my problem: Test010.xcodeproj (it's ARC enabled)

More and more I come to the conclusion that it's not a good idea to use the UIViewControllers view and assign it to the titleView but I don't see any alternative here.

Edit: Sorry, the sample project commented out the call which causes the exception. I reuploaded the linked project file.

Edit^2: As PengOne pointed out I've skipped the exact error message I got:

2011-09-10 23:09:50.621 Test010[78639:f803] -[CALayer buttonPressed:]: unrecognized selector sent to instance 0x9254ae0
2011-09-10 23:09:50.623 Test010[78639:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayer buttonPressed:]: unrecognized selector sent to instance 0x9254ae0'

回答1:

Have you tried setting NSZombieEnabled to YES? If I do this, the console shows the following output:

2011-09-10 22:56:23.329 Test010[6481:ef03] *** -[MUZTitleViewController
performSelector:withObject:withObject:]: message sent to deallocated 
instance 0x7a7ff70

As the project is ARC enabled, the controller seems to get deallocated some time after this line:

MUZTitleViewController *title = [[MUZTitleViewController alloc] initWithNibName:nil bundle:nil];

I am not sure what the best solution is, but a property definitely helps to prevent the exception like so:

// MUZDetailViewController.h
@property (strong, nonatomic) MUZTitleViewController *title;

// MUZDetailViewController.m
@synthesize title;

self.title = [[MUZTitleViewController alloc] initWithNibName:nil bundle:nil];
self.navigationItem.titleView = title.view;


回答2:

The problem that you were having with ARC can also be resolved by setting the initial view controller of your application as your main window's rootViewController property instead of using addSubview.

Doing this avoids the need to add each custom view controller as a property.