我的cpViewController有一个按钮,模态分段到cpScanViewController。我希望cpScanViewController在完成成功扫描后通过字符串通知ViewController。在网上阅读了大量文章后,我相信代表团是最好的方式吗?
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 :(得分:0)
因为您没有从receivedUPC
课程中调用cpScanViewController
方法。您需要在[_delegate receivedUPC:self]
类中添加cpViewController
,以便调用此委托方法。
答案 1 :(得分:0)
我能够通过使用以下方法使其正常工作:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
cpScanViewController *vd = (cpScanViewController *)[segue destinationViewController];
vd.delegate = self;
}
因为我在故事板中建立了连接,所以我没有意识到需要使用该方法。