background image

{
    NSString *webpageString = [[[NSString alloc]
    initWithContentsOfURL:[self targetURL]] autorelease];
    NSError *error = nil;
    NSXMLDocument *document = [[NSXMLDocument alloc]
    initWithXMLString:webpageString 
    options:NSXMLDocumentTidyHTML error:&error];
    if (!document) {
        NSLog(@"%s Error loading document (%@): %@", 
        _cmd, [[self targetURL] absoluteString], error);
         return;
    }
    [[AppDelegate shared]
    performSelectorOnMainThread:@selector(pageLoaded:)
         withObject:document waitUntilDone:YES];
    [document release];
}
@end
    正如我们所看到的那样,这个类相当的简单,在它的 init 方法中接受一个 url 并保存起来,

main 函数被调用的时候,它使用这个保存的 url 创建一个字 符串,并将这个字符串传递

NSXMLDocumentinit 方 法 。 如 果 加 载 的 xml 数 据 没 有 出 错 , 数 据 会 被 传 递 给

AppDelegate,它处于主线 程中。到此,这个线程的任务就完成了。在主线程中注销操作队列
的时候,会将这个

NSOperation 对象释放。

AppDelegate.h@interface AppDelegate : NSObject {
    NSOperationQueue *queue;
}+ 

(id)shared;- 

(void)pageLoaded:(NSXMLDocument*)document;@endAppDelegate.m 

#import "AppDelegate.h"#import "PageLoadOperation.h"@implementation AppDelegate
static AppDelegate *shared;
static NSArray *urlArray;
- (id)init
{
    if (shared)
    {
        [self autorelease];
        return shared;
    }
      if (![super init]) return nil;      NSMutableArray *array = [[NSMutableArray alloc] init];[array 
addObject:@"http://www.google.com"];[array 

addObject:@"http://www.apple.com"];[array 

addObject:@"http://www.yahoo.com"];[array  addObject:@"http://www.zarrastudios.com"];[array 
addObject:@"http://www.macosxhints.com"];urlArray  =  array;       queue  =  [[NSOperationQueue 
alloc] init];shared = self;return self;
    }
    •    (void)applicationDidFinishLaunching:
    (NSNotification *)aNotification