代表没有回应

时间:2014-03-30 08:33:50

标签: ios objective-c delegates protocols

我正在尝试使用我的应用中的Delegate和协议调用另一种方法。我需要将变量“myData”发送到另一个视图但由于某些原因它不起作用。我不知道代理和协议的实现我做错了什么。代表从不调用协议的动作。

抱歉,我对此很新。

BLEViewController.h

#import <UIKit/UIKit.h>
#import "BLE.h"

@protocol EnviarDatos <NSObject>
//Metodo que se manda llamar pero se implementa en otra clase
-(void) actualizaDatos:(NSData*)Data;
@end

@interface BLEViewController : UITableViewController <BLEDelegate>
{
    //id <EnviarDatos> delegate;
}

@property (nonatomic,assign)id delegate;

@property (nonatomic, retain) NSData *myData;
+ (BLE*) theBLEObject;

- (void) scanForPeripherals;
- (IBAction)connect:(id)sender;
-(void) activaProtocolo;

@end

BLEViewController.m

//
//  BLEViewController.m
//  DL_RemoteBLE_02
//
//  Created by Dave Lichtenstein on 3/16/14.
//  Copyright (c) 2014 Dave Lichtenstein. All rights reserved.
//

#import "BLEViewController.h"

static BLE* ble;
static UILabel *statusLabel;
static NSString* connectionStatus = @"Not connected!";


@interface BLEViewController ()

@end

@implementation BLEViewController

@synthesize delegate;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    if(ble==nil)
    {
        // Create our Bluetooth Low Energy object
        //
        ble = [[BLE alloc] init];
        [ble controlSetup];
        ble.delegate = self;
    }


        // Create a toolbar at the bottom of the screen to show status text, etc.
        //

        // get screen size
        //
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        CGFloat screenWidth = screenRect.size.width;
        CGFloat screenHeight = screenRect.size.height;

        CGFloat toolbarHeight = 50.0;
        CGFloat labelHeight = 50.0;

    if(statusLabel==nil) // only create once
    {
        // create our status label object
        //
        statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, screenHeight-toolbarHeight-labelHeight, screenWidth, labelHeight)];

        statusLabel.backgroundColor = [UIColor clearColor];
        statusLabel.textColor = [UIColor blackColor];
        statusLabel.font = [UIFont boldSystemFontOfSize:15];

        statusLabel.text = @"Connection Status:";
    }


    // create a toolbar
    //
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,screenHeight-toolbarHeight,screenWidth,toolbarHeight)];

    toolbar.tintColor = [UIColor blackColor];

    /*UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 150, 20)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor blackColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    label.text = @"Status:";
    UIBarButtonItem *labeltext = [[UIBarButtonItem alloc] initWithCustomView:label];
    UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:nil];

    NSArray *items = [NSArray arrayWithObjects:statusLabel, nil];
    toolbar.items = items;
    */

    [self.view addSubview:statusLabel];
    [self.view addSubview:toolbar];


    // Update our status label
        statusLabel.text = connectionStatus;
    _myData = [[NSData alloc]init];
    delegate = self;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-------------------------------------------------------
// methods
/////////////////////////////////////////////////////////
+ (BLE*) theBLEObject
{
    return ble;
}


-(void) connectionTimer:(NSTimer *)timer
{


    if (ble.peripherals.count > 0)
    {
        [ble connectPeripheral:[ble.peripherals objectAtIndex:0]];
    }
    NSLog(@"connectionTimer"); // diag
}

// We call this when the view loads to try to connect to our bluetooth perepheral
//
- (void) scanForPeripherals
{
    if (ble.activePeripheral)
        if(ble.activePeripheral.state == CBPeripheralStateConnected)
        {
            statusLabel.text = @"Disconnectng from peripheral...";
            [[ble CM] cancelPeripheralConnection:[ble activePeripheral]];
            return;
        }

    if (ble.peripherals)
        ble.peripherals = nil;


    NSLog(@"scanning...");
    statusLabel.text = @"Scanning for peripherals...";

    [ble findBLEPeripherals:2];

    [NSTimer scheduledTimerWithTimeInterval:(float)2.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:NO];

    //[indConnecting startAnimating];
}

- (IBAction)connect:(id)sender {

    [self scanForPeripherals];
}


///////////////////////////////////////////////////////////
#pragma mark - BLE delegate
///////////////////////////////////////////////////////////

NSTimer *rssiTimer;

// When Connected, this will be called
-(void) bleDidConnect
{
    NSLog(@"->Connected");
    statusLabel.text = @"Connected!";
    connectionStatus = @"Connected!";


    // Schedule to read RSSI every 1 sec.
    rssiTimer = [NSTimer scheduledTimerWithTimeInterval:(float)1.0 target:self selector:@selector(readRSSITimer:) userInfo:nil repeats:YES];

}


// When RSSI is changed, this will be called
-(void) bleDidUpdateRSSI:(NSNumber *) rssi
{
    // Append the rssi value to our status label
    //
    NSString *temp = [NSString stringWithFormat:@"%@ (%@)", connectionStatus, rssi];

    statusLabel.text = temp;
}

-(void) readRSSITimer:(NSTimer *)timer
{
    [ble readRSSI];
}

// When data is comming, this will be called
-(void) bleDidReceiveData:(unsigned char *)data length:(int)length
{
    NSData *d = [NSData dataWithBytes:data length:length];
    _myData = [NSData dataWithBytes:data length:length];
    NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
    NSLog(@"Datos en String %@",s);

    //_datosdelegate = self;

    //Is anyone listening
    if([delegate respondsToSelector:@selector(actualizaDatos:)])
    {
        //send the delegate function with the amount entered by the user
        [delegate actualizaDatos:_myData];
        NSLog(@"Entro delegado");
    }


}

- (void)bleDidDisconnect
{
    NSLog(@"->Disconnected");
    connectionStatus = @"Disconnected!";
    statusLabel.text = @"Disconnected!";

    [rssiTimer invalidate];
}

@end

sevenSegmentsViewController.h

#import <UIKit/UIKit.h>
#import "BLEViewController.h"
#import "BLE.h"

@interface sevenSegmentsViewController : UIViewController<EnviarDatos>{
    UIImage *unoON;
    UIImage *dosON;
    UIImage *tresON;
    UIImage *cuatroON;
    UIImage *cincoON;
    UIImage *seisON;
    UIImage *sieteON;

    UIImage *unoOFF;
    UIImage *dosOFF;
    UIImage *tresOFF;
    UIImage *cuatroOFF;
    UIImage *cincoOFF;
    UIImage *seisOFF;
    UIImage *sieteOFF;

}
@property (strong, nonatomic) IBOutlet UIImageView *uno;
@property (strong, nonatomic) IBOutlet UIImageView *dos;
@property (strong, nonatomic) IBOutlet UIImageView *tres;
@property (strong, nonatomic) IBOutlet UIImageView *cuatro;
@property (strong, nonatomic) IBOutlet UIImageView *cinco;
@property (strong, nonatomic) IBOutlet UIImageView *seis;
@property (strong, nonatomic) IBOutlet UIImageView *siete;

@end

sevenSegmentsViewController.m

//
//  sevenSegmentsViewController.m
//  iShield
//
//  Created by Victor Carreño on 29/03/14.
//  Copyright (c) 2014 RedBearLab. All rights reserved.
//

#import "sevenSegmentsViewController.h"

@interface sevenSegmentsViewController ()

@end

@implementation sevenSegmentsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    unoOFF = [UIImage imageNamed:@"7segnh.png"];
    dosOFF = [UIImage imageNamed:@"7segnv.png"];
    tresOFF = [UIImage imageNamed:@"7segnv.png"];
    cuatroOFF =[UIImage imageNamed:@"7segnh.png"];
    cincoOFF = [UIImage imageNamed:@"7segnh.png"];
    seisOFF = [UIImage imageNamed:@"7segnv.png"];
    sieteOFF = [UIImage imageNamed:@"7segnh.png"];

    unoON = [UIImage imageNamed:@"7segvh.png"];
    dosON = [UIImage imageNamed:@"7segvv.png"];
    tresON = [UIImage imageNamed:@"7segvv.png"];
    cuatroON =[UIImage imageNamed:@"7segvh.png"];
    cincoON = [UIImage imageNamed:@"7segvh.png"];
    seisON = [UIImage imageNamed:@"7segvv.png"];
    sieteON = [UIImage imageNamed:@"7segvh.png"];

    _uno = [[UIImageView alloc]initWithImage:unoOFF];
    _dos = [[UIImageView alloc]initWithImage:dosOFF];
    _tres = [[UIImageView alloc]initWithImage:tresOFF];
    _cuatro = [[UIImageView alloc]initWithImage:cuatroOFF];
    _cinco = [[UIImageView alloc]initWithImage:cincoOFF];
    _seis = [[UIImageView alloc]initWithImage:seisOFF];
    _siete = [[UIImageView alloc]initWithImage:sieteOFF];

    //BLEViewController *myBLE = [[BLEViewController alloc]init];
    //BLE *myBLE = [BLEViewController theBLEObject];
    //NSLog(@"%@", myBLE.myData);

    BLEViewController *myBLE = [[BLEViewController alloc]init];
    myBLE.delegate = self;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark Delegado de Actualizar datos

-(void) actualizaDatos :(NSData *)myData{

    NSLog(@"Datos recividos");
    NSLog(@"Imprimio mi data con exitos %@", myData);

}

@end

1 个答案:

答案 0 :(得分:0)

简而言之,当我认为您希望将其设置为“sevenSegmentsViewController”的实例时,您的BLEViewController将其委托属性设置为“self”。结果是“if([delegate respondsToSelector:...”测试失败,你永远不会调用actualizaDatos。如果你正确使用协议,你根本不需要测试“respondsToSelector”,因为根据定义,代表必须支持该协议。

编译器和IDE没有向您显示错误,因为您声明BLEViewController的属性只是键入“id”而不是

id<EnviarDatos> 

如果你修改了属性声明,说你的委托必须支持正确的协议,你会立即看到突出显示的错误。