0

I am having trouble using a protocol to get some data from another class. I can't see how to set the delegate in a class that doesn't segue to the MVC that needs the data. I create the protocol in the MVC and implement the method(s) in some arbitrary class that contains the data I need. But I can't see how to refer back to the delegator MVC to set the delegate if there is no reference to the delegator MVC, like when you use segue.destinationViewController.

Bob
  • 559
  • 1
  • 5
  • 18
  • That's a bit hard to understand. Can you post some code, please? – emrys57 Nov 30 '12 at 17:12
  • I don't have any code to post that would help because I don't know how to do this so I'll try to explain it better. I have an MVC (MyViewController) that puts some data into a view. Sometimes I need additional data from some other class (SomeDataClass). I create a protocol with a method and a delegate in MyViewController. I implement the protocol method in SomeDataClass. Now, how do I set the delegate in MyViewController to point to SomeDataClass as the delegate? I don't have a reference to MyViewController, so can't reference the delegate to set it. – Bob Nov 30 '12 at 17:27

3 Answers3

1

Something like this?

@implementation MyViewController {
// keep a pointer to the data supplier class as long as this object exists
// so that it will continue to exist and send me delegate callbacks
SomeDataClass *myInstanceOfSomeDataClass; // instance variable to point to my data supplier
}

// ...

- (void)updateMyView {
    if (myInstanceOfSomeDataClass == NULL) // I haven't created an instance yet
        myInstanceOfSomeDataClass = [[SomeDataClass alloc] init];
    SomeType *results;
    if (instantResultsAreAvailable)
        results = [myInstanceOfSomeDataClass getResults];
    if (resultsAreOnlyAvailableFromDelegateCallback)
        myInstanceOfSomeDataClass.delegate = self;
}

- (void) delegateCallbackMethod {
//...
}
@end
emrys57
  • 6,679
  • 3
  • 39
  • 49
  • OK, so if there is no existing relationship between the 2 classes and I don't want to make an instance, there is no way to use delegation. – Bob Nov 30 '12 at 22:34
1

If MyViewController can create the instance of SomeDataClass, then you set the delegate there. If there is no connection between the controllers, then you might use an NSNotification instead. That is a completely anonymous way to connect instances -- you send out a notification, and any class that registers for that notification can get it.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • That is the solution I was considering, but wanted to take a shot at using delegation to do this if possible. Looks like it isn't for what I wanted to do. – Bob Nov 30 '12 at 22:35
0

you want to pass data from one from viewcontroller to another class? just go through this Passing Data between View Controllers

Community
  • 1
  • 1
kumar_android
  • 2,273
  • 1
  • 21
  • 30