我正在尝试使用Delegates通过视图控制器进行通信。这是我的代码:
@protocol ViewControllerDelegate;
@interface ViewController : UIViewController <UITextFieldDelegate>{
IBOutlet UIDatePicker *dateTimePicker;
}
@property (nonatomic, strong) IBOutlet UITextField *className;
@property (nonatomic, strong) IBOutlet UITextField *assignmentTitle;
@property (nonatomic, strong) IBOutlet UITextField *assignmentDescription;
@property (nonatomic, strong) IBOutlet UISwitch *procrastinationNotificationSwitch;
@property (nonatomic, strong) IBOutlet UILabel *notificationOnOffLabel;
@property (nonatomic, assign) id <ViewControllerDelegate> delegate;
@property (nonatomic,strong)classObject *classObject;
-(IBAction) addButton:(id)sender;
@end
@protocol ViewControllerDelegate <NSObject>
-(void)assignmentSaved:(classObject *)classObj;
行动中:
[self.delegate assignmentSaved:self.classObject];
在其他视图控制器中:
-(ViewController *)vc
{
if (!_vc) {
_vc = [[ViewController alloc]init];
}
return _vc;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.vc.delegate = self;
}
-(void)assignmentSaved:(classObject *)classObj
{
NSLog(@"%@",classObj.description);
classObj2 = classObj;
[self.tableView reloadData];
}
vc是View Controller
的属性。当我NSLog代表时,代表最终为零。我也试过@mialkan答案但它仍然无法正常工作。如果您需要更多信息,请询问。
答案 0 :(得分:1)
我对你的代码进行了一些更改,不要忘记@synthesize delegate;
,也不要忘记创建ViewController的setDelegate:self。
@protocol ViewControllerDelegate;
@interface ViewController : UIViewController <UITextFieldDelegate>{
IBOutlet UIDatePicker *dateTimePicker;
id <ViewControllerDelegate> delegate;
}
@property (nonatomic, strong) IBOutlet UITextField *className;
@property (nonatomic, strong) IBOutlet UITextField *assignmentTitle;
@property (nonatomic, strong) IBOutlet UITextField *assignmentDescription;
@property (nonatomic, strong) IBOutlet UISwitch *procrastinationNotificationSwitch;
@property (nonatomic, strong) IBOutlet UILabel *notificationOnOffLabel;
@property (nonatomic, assign) id <ViewControllerDelegate> delegate;
@property (nonatomic,strong)classObject *classObject;
-(IBAction) addButton:(id)sender;
@end
@protocol ViewControllerDelegate
-(void)assignmentSaved:(classObject *)classObj;
@end
答案 1 :(得分:0)
在第一个视图中,您订阅了您的代表&lt; ViewControllerDelegate&gt; ?
MyOtherViewController : UIViewController <ViewControllerDelegate>
你只能这样做:
- (void)viewDidLoad
{
[super viewDidLoad];
if (!_vc)
_vc = [[ViewController alloc]init];
self.vc.delegate = self;
}