开发者

Creating an object to act as a delegate - Objective C

开发者 https://www.devze.com 2022-12-17 01:17 出处:网络
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?

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 开发者_JS百科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?


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];


Check out this answer, I think it covers what you need: How to use custom delegates in Objective-C

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号