委托方法未调用

时间:2012-07-16 08:13:57

标签: iphone objective-c xcode delegates

作为初学者,我发现很难理解代表,所以我会尽力问我的问题:

我希望Connection.m成为Controller.h的委托。 在我的Controller.h中我有

@protocol HeliControllerDelegate <NSObject>

@optional
- (void) measurementUpdated:(NSNumber *) measurement;
- (void) didDiscoverCharacteristic; // neh

@end

@interface HeliController : UIViewController <CBPeripheralDelegate>
@property (nonatomic, assign) id<HeliControllerDelegate> delegate;
@end

并在Controller.m中合成:

@synthesize delegate = _delegate;
接口解除之前

。在Controller.m中,我用

调用didDiscoverCharacteristic
- (void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{

NSLog(@"Did discover characteristic for service %@", [service.peripheral UUID]);

for(CBCharacteristic *c in [service characteristics]){

    if([[c UUID] isEqual:HeliController.throttleCharacteristicUUID]){

        NSLog(@"Found throttle characteristic");

        self.throttleCharacteristic = c;

        [self.delegate didDiscoverCharacteristic];

    }
}
}

在委托文件Connection.h中,我以

开头
@interface Connection : UIViewController <CBCentralManagerDelegate, ControllerDelegate> {
}

这样我就可以使用Controller.h的协议中的方法,但即使程序执行了didDiscoverCharacteristic调用,Connection.m中的方法实现也没有任何反应。

非常感谢所有对此的帮助。

4 个答案:

答案 0 :(得分:1)

您是否在Controller.h文件中声明了委托?

@interface Controller 
{
    id (ControllerDelegate) controllerDelegate;
}
@property (nonatomic, assign) id (ControllerDelegate) controllerDelegate;

使用&lt;&gt;控制器委托的括号而不是() 并在.m文件中添加以下内容

 @synthesize controllerDelegate 

答案 1 :(得分:1)

你仍然错过了一些东西:

你必须告诉你的实例“Controller”哪个实例是它的委托,这意味着你必须创建一个属性(称之为“委托”或类似于“myDelegate”的东西)并将其设置为指向一个实例使用该协议的类(在您的情况下为Connection)。

它应该适用于UITable的代理(例如,使用协议UITableViewDelegate)

你需要告诉你的UITableView谁(哪个实例)可以“听到”调用tableView:didSelectRowAtIndexPath:和其他委托方法

设置指向它的表实例属性:

yourTable.delegate = anInstanceOfADelegateClass;

答案 2 :(得分:0)

在您调用self.delegate时,Controller.m didDiscoverCharacteristic可能为零。您可以使用调试器或NSLog()进行检查。确保将Controller对象的委托@property设置为正确的Connection实例。

答案 3 :(得分:0)

  1. 在ControllerDelegate无意义之后的NSObject

  2. 在Controoler类中声明委托属性