I am developing a game that uses a different controller for each level. It needs to detect a shake via the accelerometer, so it registers itself as a delegate like so:
UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = kUpdateInterval;
When the level ends, this controller gets dealloc'd and freed. Previously, I was getting a crash after this controller was freed because I didn't nil out the delegate on UIAccelerometer (i.e. it was still sending events to an object that has now been freed). So now, inside of dealloc, I'm doing this:
UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = nil;
All is well and good and the first level plays without a hitch. The problem happens when I get to the next level, create a new level controller and run that first batch of code again (setting the new contoller now as the delegate). After this, I'm not getting any calls from the Accelerometer.
So the question is, are you only allowed to have one delegate per app for the Accelerometer, or am I just missing something? I haven't seen anything in the docs that disallows setting the delegate multiple times. I'm slightly new to Obj-C, but as far as I understand delegates this shouldn't be too unorthodox.
Note: I know that in 3.0 I could just listen for shake notifications. Unfortunately, I need something else to be first responder the entire time I'm interested in the shake. So I can't just refactor to that option.
In general, objects that have delegates have only one at a time. Unless otherwise documented, there shouldn't be any limitations on setting more than one different object as delegate over the lifetime of a particular instance.
I wonder if what's happening is that your first controller is being
dealloc
ed after you set the second controller as the accelerator delegate. Have you watched that code with the debugger to be sure that everything's happening in the order you expect?