开发者

Class not receiving delegate notifications

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;
}

T开发者_StackOverflow中文版he 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜