代表不通知我的观点

时间:2014-09-12 13:51:44

标签: objective-c ios7 delegates

我的cpViewController有一个按钮,模态分段到cpScanViewController。我希望cpScanViewController在完成成功扫描后通过字符串通知ViewController。在网上阅读了大量文章后,我相信代表团是最好的方式吗?

  1. 委托是否设置正确?
  2. 委托如何通知cpViewController?
  3. cpScanViewController.h

    #import <UIKit/UIKit.h>
    
    
    @protocol ScanDelegate <NSObject>
    -(void)receivedUPC:(NSString *)Scan;
    @end
    
    @interface cpScanViewController : UIViewController 
    @property (nonatomic, weak) id <ScanDelegate> delegate;
    @property (nonatomic, retain) NSString *UPC;
    -(void)checkUPC;
    @end
    

    cpScanViewController.m

    @interface cpScanViewController ()
    {
      NSString *UPC;
    }
    @end
    
    @implementation cpScanViewController
    @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];
    // Do any additional setup after loading the view.
    }
    -(void)doSomeScanStuff
    {
    UPC = @"a string"
       // even tried
     [delegate receivedUPC:UPC];
    }
    -(void)checkUPC
    {
    
    }
    @end
    

    cpViewController.h

    #import <UIKit/UIKit.h>
    #import "cpScanViewController.h"
    
    @interface cpViewController : UIViewController <ScanDelegate>
    
    @end
    

    cpViewController.m

    @interface cpViewController ()
    {
     cpScanViewController *cp;
    }
    @end
    
    @implementation cpViewController
    
    - (void)viewDidLoad
    {
      // set delegate
    cp = [[cpScanViewController alloc] init];
    [cp setDelegate:self];
    
    }
    -(void)receivedUPC:(NSString *)Scan{
      // Nothing happening
    NSLog(@"%@", Scan);    
    NSLog(@"The %@", cp.UPC);
    }
    @end
    

2 个答案:

答案 0 :(得分:0)

因为您没有从receivedUPC课程中调用cpScanViewController方法。您需要在[_delegate receivedUPC:self]类中添加cpViewController,以便调用此委托方法。

答案 1 :(得分:0)

我能够通过使用以下方法使其正常工作:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    cpScanViewController *vd = (cpScanViewController *)[segue destinationViewController];
vd.delegate = self;
}

因为我在故事板中建立了连接,所以我没有意识到需要使用该方法。