我有一个类调用另一个类从 URL 解析(NSXMLParse)。现在我想让调用这个的类知道它什么时候完成,这样我就可以填充 UI。我猜想一个代表将是要走的路,但我从未与一个代表合作过,并且需要一些关于如何连接的指导。
谢谢
我有一个类调用另一个类从 URL 解析(NSXMLParse)。现在我想让调用这个的类知道它什么时候完成,这样我就可以填充 UI。我猜想一个代表将是要走的路,但我从未与一个代表合作过,并且需要一些关于如何连接的指导。
谢谢
在我看来,NSNotification 是设置此类内容的最简单方法。
这是我的一个应用程序的一个小片段:
当我正在处理的事情完成时,在 method.m 中
[[NSNotificationCenter defaultCenter] postNotificationName:@"GlobalTagsReady" object:nil];
在课堂上处理通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getTags) name:@"GlobalTagsReady" object:nil];
@selector(getTags)
要调用的方法在哪里
基本上,委托只是意味着给一个对象一个指向它需要告诉它正在做什么的指针。在 Cocoa 中,这通常是通过“协议”来处理的,这与接口声明有点相反:它们描述了一个对象将在另一个“实现”协议的对象上调用哪些方法。严格来说,它们不是必需的,尤其是在这种简单的情况下,但它们是一种很好的做法,并且知道你是否要编写模块化代码是一件好事。
在解析类的标题中:
// This is the protocol declaration; anything implementing the "ParsingDelegate" protocol needs to have any method signatures listed herein
@protocol ParsingDelegate
- (void)parsingDidEndWithResult:(NSDictionary *)result
@end
@interface ParsingClass : NSObjectOrWhatever
{
...
id<ParsingDelegate> _delegate;
}
...
// We'll use this property to tell this object where to send its messages
@property(nonatomic,assign) id<ParsingDelegate> delegate;
@end
在解析器的实现中:
@implementation ParsingClass
@synthesize delegate=_delegate;
// the "=_delegate" bit isn't necessary if you've named the instance variable without the underscore
...
在解析器完成其内容的方法中:
...
// make sure the delegate object responds to it
// assigning an object that doesn't conform to the delegate is a warning, not an error,
// but it'll throw a runtime exception if you call the method
if(self.delegate && [self.delegate respondsToSelector:@selector(parsingDidEndWithResult:)])
{
[self.delegate performSelector:@selector(parsingDidEndWithResult:) withObject:someResultObject];
}
...
在 UI 类的标题中:
@interface SomeUIClass : NSObjectOrWhatever <ParsingDelegate>
在 UI 类中,无论它设置解析器,
parser.delegate = self;
然后只需-parsingDidEndWithResult:
在 UI 类上实现该方法。如果您同时运行多个解析器,您可能希望扩展委托方法以传入解析器对象本身——这是 Cocoa 标准的一种——但对于您描述的情况,这应该可以解决问题。
你在 cocoa 中主要有 3 种对话方式:delegate、notifications 和 KVO。(参见http://alexvollmer.com/index.php/2009/06/24/cocoas-ways-of-talking/)
我假设您正在后台线程中获取数据并解析 XML。因此,无论您要使用什么解决方案,请记住在主线程中更新 UI(例如使用 performSelectorOnMainThread)