views:

129

answers:

1

I have created a class (TestAccel) that implements UIAccelerometerDelegate. I have a private var in this class for UIAccelerometer.

UIAccelerometer *accel;

The class init looks like this:

- (id) init:(id)actOnThisInstance{
[self init];
accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = actOnThisInstance;
return self;
}

The caller (a ViewController) initializes like this

accel = [[Acc alloc]init:self];

TestAccel never receives any notifications to its implementation of shouldAutorotateToInterfaceOrientation. I then implement UIAccelerometerDelegate in the caller. The caller receives notifications but TestAccel still receives nothing. Any ideas what I'm doing wrong?

My goal is to create a class that is self contained in handling UIAccelerometerDelegate notifications for a calling class. I'd like the caller to not implement UIAccelerometerDelegate but not sure if that is possible.

+1  A: 

You do not need to pass in an object to assign as the delegate of the accelerometer if you just want to assign "self". You are actually assigning the view controller as the delegate (in the view controller, "self" is the view controller).

You probably don't need multiple init methods for the TestAccel class. This is just a recommendation though. Of course, remember to call [super init] first if you do go with just one method. For example:

- (id) init {
    if (self = [super init]) {
        // other TestAccel init stuff here
        accel = [UIAccelerometer sharedAccelerometer];
        accel.delegate = self; // assign self as delegate
    }
    return self;
}

And, in the view controller, you should alloc and init a TestAccel object (not an Acc object):

accel = [[TestAccel alloc] init];

Also, TestAccel should implement the UIAccelerometerDelegate protocol and your view controller should not.

UPDATE
Use better coding practice for setting self in its init method.

gerry3
+1 Good answer. I would recommend using: `if (!(self = [super init])) { return nil; }` instead of simply `[super init]`. See the conclusion at: http://www.wilshipley.com/blog/2005/07/self-stupid-init.html
e.James
Thanks. Acc alloc was a typo. I've followed along with what you have but still don't get notifications in TestAccel. It has implemented the delegate: @interface TestAccel : NSObject<UIAccelerometerDelegate>. Strange thing is that if I implement shouldAutorotateToInterfaceOrientation in the viewcontroller, it will get the notification, although it doesn't implement the delegate. Any ideas?
4thSpace
shouldAutorotateToInterfaceOrientation: is a UIViewController method that can be overridden. It is not related to UIAccelerometerDelegate which has just one method to implement: accelerometer:didAccelerate:.
gerry3
Yes - my bad. didAccelerate is receiving notifications in TestAccel. Thanks.
4thSpace
If you found this answer useful, you could accept it.
gerry3