Saturday, December 4, 2010

Error: unrecognized selector sent to instance

The error means an object does not respond to a selector sent to it. Various reasons can cause this error. Today I found another one: assigning to instance variable in class method can corrupt an object and cause it not to respond to a selector which it should.

For example, you have a view controller vc. By all means you expect [vc.view addSubview:anotherView] should work but you got error:

(null): unrecognized selector sent to instance 0xblah

Then you found that this view controller has a class method which updates some instance variables. Since it worked before, you think it is OK to do that. However, after some other coding, the application was suddenly broken, and you got that error. You can still NSLog(@"%@",vc.view) and it seems to be fine, but when you check [vc.view respondsToSelector:@selector(addSubview:)] you get NO.

This is totally insane. Then you noticed the compiler output:

warning: instance variable 'adView' accessed in class method

Then you remember you did something dubious: modifying instance variable in class method. In C++ such code won't compile but in objective-c it is just a warning.

After fixing this, the error disappeared.

The lessons learned:
1. Do not access instance variables in class method. Even if it works today, it may break tomorrow.
2. Pay attention to warnings. They said bad C++ code is like bullets which can shoot your toe. I would say objective-c is even worse.

No comments:

Post a Comment