Objective-C 代表:有另一个我称之为解析 XML 的类。需要知道何时在外部完成
我有一个类调用另一个类来从 URL 解析 (NSXMLParse)。现在我想让调用这个类的类知道它何时完成,以便我可以填充 UI。我猜委派是一种可行的方法,但我从未与委派合作过,并且需要一些关于如何连接的指导。
谢谢
I have a class that calls another class to parse (NSXMLParse) from a URL. Now I would like for the class calling this one to know when it has finished, so that I can populate the UI. I am guessing a delegate would be the way to go but ive never worked with one and would need some guidance as to how this would be wired.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我看来,NSNotification 是设置此类内容的最简单方法。
这是我的一个应用程序中的一个小片段:
在 method.m 中,当我正在处理的内容在类中完成时
,以处理通知,
其中
@selector(getTags)
是方法称为NSNotification is, in my opinion, the easiest way to setup something like this.
This is a small snippet from one of my apps:
in method.m when the something I'm processing has finished
in the class to take care of the notification
where
@selector(getTags)
is the method to be called基本上,委托只是意味着给一个对象一个指向它需要告诉它正在做什么的东西的指针。在 Cocoa 中,这通常是通过“协议”来处理的,这有点与接口声明相反:它们描述了一个对象将在另一个“实现”协议的对象上调用什么方法。严格来说,它们并不是必需的,尤其是在像这样的简单情况下,但它们是很好的实践,并且如果您要编写模块化代码,了解它们是一件好事。
在解析类的标头中:
在解析器的实现中:
在解析器完成其工作的方法中:
在 UI 类的标头中:
在 UI 类中,无论它在何处设置解析器,
只需实现
-parsingDidEndWithResult: UI 类上的
方法。如果您同时运行多个解析器,您可能希望扩展委托方法以传入解析器对象本身(这是 Cocoa 标准),但对于您所描述的情况,这应该可以解决问题。Basically, delegation just means giving an object a pointer back to something that it needs to tell about what it's doing. In Cocoa, this is usually handled through “protocols”, which are sort of the reverse of an interface declaration: they describe what methods an object will call on another object that “implements” the protocol. They're not, strictly speaking, necessary, particularly in a simple situation like this, but they're good practice and a good thing to know if you're going to be writing modular code.
In the parsing class's header:
In the parser's implementation:
In the method in which the parser finishes its stuff:
In the UI class's header:
In the UI class, wherever it sets up the parser,
then just implement the
-parsingDidEndWithResult:
method on the UI class. If you have multiple parsers running at once, you might want to extend the delegate method to pass in the parser object itself—that's kind of the Cocoa standard—but for the case you've described, this should do the trick.在 cocoa 中你主要有 3 种方式进行交谈:委托、通知和 KVO。 (参见http://alexvollmer.com/index .php/2009/06/24/cocoas-ways-of-talking/)
我假设您正在后台线程中获取数据并解析 XML。因此,无论您要使用哪种解决方案,请记住更新主线程中的 UI(例如使用 PerformSelectorOnMainThread)
You mainly got 3 ways to talk in cocoa: delegates, notifications and KVO. (cf http://alexvollmer.com/index.php/2009/06/24/cocoas-ways-of-talking/)
I assume that you are fetching the data and parsing the XML in a background thread. So whatever solution you are going to use, keep in mind to update the UI in the mainthread (using performSelectorOnMainThread for instance)