2014-09-12 34 views
1

我的cpViewController有一个按钮,该按钮的模式继续到cpScanViewController。我想让cpScanViewController在成功扫描完成后通知ViewController一个字符串。在网上阅读了大量文章后,我相信代表团是实现这一目标的最佳方式吗?代表不通知我查看

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

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 

回答

0

我能得到它的工作使用方法:

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

因为我做的故事板的连接我没有意识到它需要有方法。

0

因为您没有从您的cpScanViewController类中调用receivedUPC方法。您需要添加[_delegate receivedUPC:self],其中一些用于在cpViewController类中调用此委托方法。

+0

加入[delegate receivedUPC:self];到cpScanViewController中的viewDidLoad产生并警告不兼容的指针类型,将'cpScanViewController *'发送给'Scanner *'类型的参数。 – iDev 2014-09-12 14:05:59