Reputation: 6940
I want to pass data from one of my controller to another. For that purpose i implement delegate in second view controller (it called when use tap "plus" button on first view controller):
Declaration of delegate:
@protocol AddTaskDelegate <NSObject>
-(void)addTask:(NSString*)task byDate:(NSDate*)date;
@end
Implementation of delegate:
- (IBAction)addTask:(id)sender {
if ([self.addTextField.text length] >0){
NSDate *now = [NSDate date];
[self.delegateObj addTask:self.addTextField.text byDate:now];
[self dismissViewControllerAnimated:YES completion:nil];
} else {
NSLog(@"You should type something");
}
}
In viewController1
:
addController.delegateObj = self;
...
Then:
-(void)addTask:(NSString *)task byDate:(NSDate *)date {
myDateToFill = date;
myStringToFill = task;
NSLog(@"myStringToFill is - %@", task);
NSLog(@"method called");
}
However, addTask
method not called (it suppose to return values calculated in second view controller). What did i miss?
UPDATE:
I update my addTask
method for following and figure out my delegate object is nil:
- (IBAction)addTask:(id)sender {
if ([self.addTextField.text length] >0){
NSDate *now = [NSDate date];
NSLog(@"Prepare for repair");
if (self.delegateObj == nil){
NSLog(@"ALARM");
}
[self.delegateObj customMethod];
[self.delegateObj taskAdded:self addTask:self.addTextField.text byDate:now];
[self dismissViewControllerAnimated:YES completion:nil];
} else {
NSLog(@"You should type something");
}
}
Now in console i can see "Alarm" output, which tell me that self.delegateObj is nil for some reason.
Updated. Solved after that (and removing reference to AddTask controller from implementation):
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Если нету navigation Controller'a
if ([segue.identifier isEqualToString:@"add"]){
UINavigationController *navController = [segue destinationViewController];
AddViewController *addController = (AddViewController*)([navController viewControllers][0]);
addController.delegate = self;
}
}
Upvotes: 1
Views: 341
Reputation: 16793
Have you implemented the following in the ViewController1.h
?
@interface ViewController1<AddTaskDelegate>
// ...
@end
and
in the AddTaskDelegate.h, the following line is missing
@property (nonatomic, weak) id <AddTaskDelegate> delegate;
in the AddTaskDelegate.m, add the following
@synthesize delegate;
Additionally, I highly recommend you take a look at the following thread espcially @Tibidabo's answer: How do I create delegates in Objective-C?
Upvotes: 1