我已经创建了一个委托,所以我的两个不同的视图控制器可以进行通信,我试图在我的子视图控制器中将BOOL设置为YES。
childViewController.h
@protocol pageTwoViewControllerDelegate;
@interface pageTwoViewController : UIViewController {
UIButton *takePhotoTransition;
}
@property (nonatomic, weak) id<pageTwoViewControllerDelegate> delegate;
@end
@protocol pageTwoViewControllerDelegate <NSObject>
- (BOOL)didPushTakePhoto;
@end
childViewController.m
...
- (IBAction)takePhotoTransition:(id)sender {
id<pageTwoViewControllerDelegate> strongDelegate = self.delegate;
if ([strongDelegate respondsToSelector:@selector(didPushTakePhoto)]) {
strongDelegate.didPushTakePhoto = YES; // ERROR: No setter method for 'setDidPushTakePhoto:' for assignment property
}
NSLog(@"Button push recieved");
}
当按下按钮时,如何通过此错误并将我的BOOL设置为YES?
答案 0 :(得分:1)
协议只是通过协议告诉每个人都知道你的类,属性anObject将在那里。协议不是真实的,它们本身没有变量或方法
尝试将代码修改为这样,设置非存在变量或属性。
您必须实施新的课程而不是ID
你的协议看起来像
@protocol pageTwoViewControllerDelegate <NSObject>
- (void)setdidPushTakePhoto:(BOOL)aBOOL;
- (BOOL)didPushTakePhoto;
@end
并且您的class.h将包含
@property (nonatomic, getter=get_didPushTakePhoto) BOOL didPushTakePhoto;
并且您的class.m将包含实现
-(BOOL)didPushTakePhoto
{
return _didPushTakePhoto;
}
- (void)setdidPushTakePhoto:(BOOL)aBOOL{
_didPushTakePhoto=aBool;
}
答案 1 :(得分:0)
您在方法和属性之间感到困惑。
你的协议“pageTwoViewControllerDelegate”的定义说,它应该实现一个名为“didPushTakePhoto”的方法,它返回一个BOOL值。
你要做的事情完全不同。您正在尝试设置不存在的属性。每当你访问一个后跟点“。”的东西时,它应该是该对象所属的类的属性。您定义的协议不会谈论有关该属性的任何内容。
所以在if条件中,你应该在你的委托对象上调用方法“didPushTakePhoto”,如下所示。 [strongDelegate performSelector:@selector(didPushTakePhoto)];
如果您确定您的委托实现确实已经实现了协议方法,那么由于您已经将self.delegate强制转换为声明为id的strongDelegate,因此您不需要if条件。你可以直接调用下面的方法。 [strongDelegate didPushTakePhoto];
希望这有帮助
答案 2 :(得分:0)
您是否已将ChildViewController
的代表分配给ParentViewController
?
试试这个:
<强> ParentChildViewController.m 强>
#import "ChildViewController.h"
@interface ParentViewController () <ChildDelegate>
...
-(IBAction)btnClicked:(id)sender
{
ChildViewController *ctrl = [[ChildViewController alloc] init];
ctrl._delegate = self;
// do present childViewController or similar action here
}
- (void)didPushTakePhoto: (BOOL)result{
NSLog(@"result: %d",result);
}
<强> ChildViewController.h 强>
@protocol ChildDelegate
- (void)didPushTakePhoto: (BOOL)result;
@end
@interface pageTwoViewController : UIViewController {
UIButton *takePhotoTransition;
}
@property (assign, nonatomic) id _delegate;
@end
<强> ChildViewController.m 强>
...
- (IBAction)takePhotoTransition:(id)sender {
if ([self._delegate respondsToSelector:@selector(didPushTakePhoto:)]) {
[self._delegate didPushTakePhoto:YES];
// do dismiss here
}
}