views:

250

answers:

2

My question is simple actually, how do I create an object to act as a delegate, instead of including the delegate methods in my view?

For example, I have x functionality that requires delegate methods, and they're currently setup to use self as the delegate. I'd like to put those methods in their own object so that the delegate methods can be called and do stuff if the view has ended.

What's the best way?

+1  A: 

Check out this answer, I think it covers what you need: http://stackoverflow.com/questions/645449/how-to-use-custom-delegates-in-objective-c

drewh
isnt that explaining how to create a delegate? The delegate methods etc are already created as part of the custom class object I am creating. I just dont want to put the delegate methods required in my view controller.
mootymoots
for example, NSXMLParser delegate methods - they exist, the delegate is defined, but I dont want to call them as self in my view controller... what other option do I have?
mootymoots
+2  A: 

for example, NSXMLParser delegate methods - they exist, the delegate is defined, but I dont want to call them as self in my view controller... what other option do I have?

You can specify another custom class to handle the delegate methods, if you wish. Simply create a class, call it MyXMLParserDelegate or something similar. Then, all you have to do is tell your NSXMLParser object that it should use an instance of your class as its delegate.

If you are using Interface Builder, add a new object to the XIB file, set its class to MyXMLParserDelegate, and then drag a connection from your NSXMLParser object's delegate selector to the new object.

If you are doing it programmatically, the basic operation looks like this:

MyXMLParserDelegate * myDelegate = [[MyXMLParserDelegate alloc] init];
[someXMLParser setDelegate:myDelegate];

Keep in mind, however, that delegates are not retained, so in order to do this without leaking memory, you should add an ivar of type MyXMLParserDelegate to your viewController class, and then do the following:

// in your @interface block:
{
    ...
    MyXMLParserDelegate * myDelegate;
}

// in your init method:
myDelegate = [[MyXMLParserDelegate alloc] init];

// in your awakeFromNib method (or anywhere else it seems appropriate):
[someXMLParser setDelegate:myDelegate];

// in your dealloc method:
[myDelegate release];
e.James
HiThanks - this does work, and is what I'm doing, so that's good.
mootymoots