views:

49

answers:

2

I am creating a delegate view controller and presenting it to the user to perform an action but I would like to change a NSString on the delegate view controller based on the originating view controller. For example if the delegate view controller is a delegate of viewControllerA, then display Foo, but if its a delegate of viewControllerB then display Blah. ALthough I cant figure out how to pass some sort of information that indicates what the originating view controller is. I noticed that if i do an NSLog(@"I'm from %@",[self delegate]); it will tell me what the originating view controller is, as well as the memory address, but I cant seem to translate that into an NSString object to examine its value. If theres a way to make that work, or a better way to do this then that works too...

- (IBAction)editDate {
DatePickerViewController *datePickerView = [[DatePickerViewController alloc] init];
datePickerView.delegate = self;
datePickerView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:datePickerView animated:YES];
[datePickerView release];
}
A: 

You could use the class of the delegate.

if([[self delegate] isKindOfClass:[ViewControllerA class]]) {
    [self doViewControllerAThings];
}
else {
    ...
}
anshuchimala
Having to know what kind of object your delegate is, and especially changing your behavior on that basis, is a sign that you're doing something architecturally wrong. You should replace this with a single descriptively-named delegate method that each delegate implements as it sees fit. This is called polymorphism, and integrating it into your delegate protocol in this way makes the delegating class more robust.
Peter Hosey
+2  A: 

It seems like you're using some terminology in ways that are different from what most Objective-C coders would mean.

Here you're instantiating a view controller to show as a modal view. That view controller has a property called delegate that allows it to call some methods to report changes to its state. That doesn't make it a "delegate view controller", that makes it "an object with a delegate".

You happen to be using another view controller class as the delegate, but any object that implements the methods that DatePickerViewController objects want to call to report changes could be assigned to that delegate property.


I think that the question you're asking is "how do I make the DatePickerViewController display different information depending on what kind of object it's reporting to?", and the answer is much the same as "how do I make a UILabel show different text depending on the view controller that created it?"—you set properties or call methods on in when you create it.

If you really just want to pass a string to DatePickerViewController, you could add an NSString* property to DatePickerViewController and set it with arbitrary text, with

datePickerView.myString = @"some information that you want";
Seamus Campbell