I am passing a string through a delegate and protocol. The string is received to the class correctly, but this occurs after the viewDidLoad method is called. The viewDidLoad method needs that string that is passed.
Any ideas on what I can do to get the delegate method to be called before viewDidLoad? I thought this was the idea of the delegate/protocol data passing.
Method where new view is created and pushed:
ViewControllerTwo *two = [[ViewControllerTwo alloc] initWithNibName:@"ViewControllerTwo" bundle:nil];
two.delegate = self;
[two setString:theString];
[self.navigationController pushViewController:two animated:YES];
[two release];
In ViewControllerTwo:
- (void)setString:(NSString *)str
{
self.myString = str;
}
Edit: Thanks for the input. However, I do understand how to pass this data through the init method. I have been testing protocols and delegates lately, and I wanted to see if there was a way to do this. I have successfully passed data like this in another class and it worked. The protocol method was called first setting the string. It seemed like a much cleaner way to handle passing data.
I think you might be a little confused about what
Delegationis used for and why.For example you might want to make a protocol in a
UIViewControllersubclass if you were doing some kind of action in thatViewControllerand needed to inform another subclass that that action is being taken, or of the result of that action.Now in order for the subclass that wants to know about the action(the receiver), it has to conform to that protocol in it’s header file.
You also must “set” the
delegateto thereceiving class/controller.There are many ways to get a reference to the
receiving controller/classto set it as thedelegatebut a common mistake is allocating and initializing a new instance of that class to set it as the delegate, when that class has already been created.What that does is set your newly created class as the delegate instead of the class that’s already been created and waiting for a message.What your trying to do is just pass a value to a Newly created class. Since your just creating this
UIViewControllerclass all that needed for that is a Property in thereceiver(ViewControllerTwo).In your case a
NSString:and of course don’t forget in the main:
Now there is no need for a setter in your
ViewControllerTwo.The setter and Getters are free when you use the
@synthesize. Just Pass the value over to theViewController. The implementation is identical to your code except for the delegate: