我一直在研究代表。
所以我编写代理然后运行此代码的代码。
你能告诉我这是什么问题吗?
这是我的代码。
ViewController2.h
@protocol ViewController2Delegate <NSObject>;
@required
-(void)practiceDelegateMethod:(Float32)var1 andVar2:(Float32)var2;
@end
@interface ViewController2 : UIViewController
@property (assign, nonatomic) id <CompressSetupViewControllerDelegate> delegate;
ViewController2.m
@synthesize delegate;
- (IBAction)compressSetupCancleAction:(id)sender {
[self.delegate practiceDelegateMethod:var1 andVar2:var2];
[self dismissViewControllerAnimated:YES completion:nil];
}
ViewController1.h
@interface HomeViewController : UIViewController< ViewController2Delegate >
ViewController1.m
-(void) practiceDelegateMethod:(Float32)var1 andVar2:(Float32)var2{
NSLog(@"delegate var1 : %@ var2 : %@",[NSString stringWithFormat:@"%f",var1],[NSString stringWithFormat:@"%f",var2]);
}
答案 0 :(得分:-1)
在你的HomeViewController中,当你创建ViewController2
的实例时,分配委托自我
ViewController2 *controller = [[ViewController2 alloc]init];
controller.delegate = self
答案 1 :(得分:-1)
我认为问题是由于某些问题,你没有在viewController1中获得viewController2的引用。 在viewcontroller1中获取viewController2的非零引用,然后
<ref of ViewController 2>.delegate = self
我认为你在viewcontroller1中将viewController 2引用为nil。
答案 2 :(得分:-1)
更换后尝试
@property (assign, nonatomic) id <CompressSetupViewControllerDelegate> delegate;
使用:
@property (assign, nonatomic) id <ViewController2Delegate> delegate;
答案 3 :(得分:-1)
还有另一种在viewcontrollers NSNotification
从发送邮件的班级发布通知,如:
[[NSNotificationCenter defaultCenter] postNotificationName: @"YOUR_NOTIFICATION_NAME" object: anyobjectyouwanttosendalong(can be nil)];
在您希望在发布时通知通知的视图控制器中:
在viewDidLoad中执行:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(METHOD_YOU_WANT_TO_INVOKE_ON_NOTIFICATION_RECEIVED) name:@"YOUR_NOTIFICATION_NAME" object:sameasbefore/nil];
重要!不要忘记你的viewDidUnload():
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"YOUR_NOTIFICATION_NAME" object:sameasbefore/nil];
注意: - 当它只有一个对象通知另一个时,你最好使用协议:)但在这种情况下,因为有多个视图控制器正在侦听,所以使用通知
如果您想使用协议,请参阅上面的链接