Reputation: 301
Most of the information I found involving implementing protocols and delegates involves a step where you do this;
DestinationViewController *destinationVC = [[destinationViewController alloc] init];
destinationVC.delegate = self;
But after hours of frustration because I couldn't get it to work I finally stumbled across another way to allocate the destinationVC in prepareForSegue
DestinationViewController *destinationVC = segue.destinationViewController;
destinationVC.delegate = self;
Which actually works. What was I doing wrong? It seemed using the first method my delegate was never set to self.
Upvotes: 1
Views: 800
Reputation: 2056
When instantiated from a storyboard, the initWithCoder:
methid is called, not the init
method.
DestinationViewController *destinationVC = [[destinationViewController alloc] init];
destinationVC.delegate = self;
is how you do when your controller is not from a storyboard: you init it from the code. After that you have to manually handle the transition from your source VC to your destination VC.
DestinationViewController *destinationVC = segue.destinationViewController;
destinationVC.delegate = self;
is how you do when your controller is defined in a storyboard and is the destination of a segue.
When you perform a segue, the prepareForSegue:
method of the source view controller is called, in which you should configure your destination like you want: setting properties, delegates, passing data,...
Upvotes: 2
Reputation: 2413
Here is the basic tutorial about segues, updated for Xcode 6 and above.
When you use storyboards, all necessary context provided by UIStoryboardSegue class. it holds destination view controller for you. So, you must access destination controller throw destinationViewController property.
if you want to manually add controller to your navigation stack:
{
// binds your viewController from storyboard with local instance
UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"YOUR_STORYBOARD_IDENTIFIER"];
// set your delegate
vc.delegate = self;
// push controller into navigation stack
[self.navigationController pushViewController:vc animated:YES];
}
Upvotes: 1
Reputation: 3733
There is two way you can pushController
while using UIStoryboard
.
Option 1 : taking reference of actually UIViewController
from storyboard
.
UIViewController *displayTable = [self.storyboard instantiateViewControllerWithIdentifier:@"nextViewcontroller"];
[self.navigationController pushViewController:displayTable animated:YES];
Option 2 : Using Segue
[self performSegueWithIdentifier:@"MySegue" sender:sender];
In your first case you are allocating object and assign delegate. that does't means while performing pushViewController
operation same reference is passing. so in that case two different reference is created. so you delegate is point out some other reference that doesn't exist.
may this help you.
Upvotes: 1