block和del

来源:互联网 发布:怎么备份应用数据 编辑:程序博客网 时间:2024/05/22 04:37

AppDelegate.h

#import <Cocoa/Cocoa.h>

#import "MyProtocol.h"


@interface AppDelegate : NSObject <NSApplicationDelegate,NSTableViewDataSource,NSTabViewDelegate,MyProtocol>

{

    IBOutlet NSTableView *tableView;

    NSArray *classes;

}


@end


AppDelegate.m

#import "AppDelegate.h"

#import "ScheduleFetcher.h"

#import "ScheduledClass.h"


@interface AppDelegate ()


@property (weak) IBOutletNSWindow *window;

@end


@implementation AppDelegate


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    // Insert code here to initialize your application

    [tableViewsetTarget:self];

    [tableView setDoubleAction:@selector(openClass:)];

    ScheduleFetcher *fetcher = [[ScheduleFetcheralloc]init];

    NSError *error = nil;

    classes = [fetcher fetchClassesWithError:&error];

    [tableViewreloadData];

    

    //    NSLog(@"*****************************%@", [NSThread currentThread]);

    //

    //    [fetcher fetchClassesWithBlock:^(NSArray *theClasses, NSError *error) {

    //        if (theClasses) {

    //            classes = theClasses;

    //            [tableView reloadData];

    //        }else{

    //            NSAlert *alert = [[NSAlert alloc]init];

    //            [alert setAlertStyle:NSAlertStyleCritical];

    //            [alert setMessageText:@"Error locading schedule."];

    //            [alert setInformativeText:[error localizedDescription]];

    //            [alert addButtonWithTitle:@"OK"];

    //            [alert beginSheetModalForWindow:self.window modalDelegate:nil didEndSelector:nil contextInfo:nil];

    //        }

    //        NSLog(@"qqqqqqqqqqqqqqqqqqqqqqqq%@", [NSThread currentThread]);

    //    }];

    //    NSLog(@"*****************************%@", [NSThread currentThread]);

}



- (void)applicationWillTerminate:(NSNotification *)aNotification {

    // Insert code here to tear down your application

}


#pragma mark 委托

//在tabViewItem被选中之前调用

- (BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(nullableNSTabViewItem *)tabViewItem{

    return YES;

}

//通知委托,tabView将会选择tabViewItem

- (void)tabView:(NSTabView *)tabView willSelectTabViewItem:(nullableNSTabViewItem *)tabViewItem{

    

}

//通知委托,tabView已经选择了tabViewItem。

- (void)tabView:(NSTabView *)tabView didSelectTabViewItem:(nullableNSTabViewItem *)tabViewItem{

    

}

//通知委托,tabView中的选项卡视图条目的数量已经改变。

- (void)tabViewDidChangeNumberOfTabViewItems:(NSTabView *)tabView{

    

}

#pragma mark 数据源协议

//行数

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{

    return [classescount];

}


//绑定值

- (nullable id)tableView:(NSTableView *)tableView objectValueForTableColumn:(nullableNSTableColumn *)tableColumn row:(NSInteger)row{

    ScheduledClass *c= [classesobjectAtIndex:row];

    return [c valueForKey:[tableColumn identifier]];

}


-(void)openClass:(id)sender{

    ScheduledClass *c = [classesobjectAtIndex:[tableViewclickedRow]];

    NSURL * baseUrl = [NSURLURLWithString:@"http://www.baidu.com/"];

    NSURL * url = [NSURLURLWithString:[c href] relativeToURL:baseUrl];

    [[NSWorkspacesharedWorkspace]openURL:url];//打开浏览器

}

- (void)content:(NSArray *)myClasses forError:(NSError *)error {

    if (myClasses) {

        classes = myClasses;

        [tableView reloadData];

    }else{

        NSAlert *alert = [[NSAlertalloc]init];

        [alert setAlertStyle:NSAlertStyleCritical];

        [alert setMessageText:@"Error locading schedule."];

        [alert setInformativeText:[errorlocalizedDescription]];

        [alert addButtonWithTitle:@"OK"];

        [alert beginSheetModalForWindow:self.windowmodalDelegate:nildidEndSelector:nilcontextInfo:nil];

    }

}


@end


ScheduledClass.h

#import <Foundation/Foundation.h>


@interface ScheduledClass : NSObject

{

    NSString *name;//名称

    NSString *location;//地点

    NSString *href;//链接

    NSDate *begin;//开始时间

}

@property (nonatomic,copy)NSString *name;

@property (nonatomic,copy)NSString *location;

@property (nonatomic,copy)NSString *href;

@property (nonatomic,copy)NSDate *begin;

@end


ScheduledClass.m

#import "ScheduledClass.h"


@implementation ScheduledClass

@synthesize name,location,href,begin;

@end


ScheduledFetcher.h

#import <Foundation/Foundation.h>

#import "MyProtocol.h"

//创建一个块

typedef void (^ScheduleFetcherResultBlock)(NSArray*classes,NSError*error);


//实现NSURLConnectionDataDelegate协议

@interface ScheduleFetcher :NSObject<NSXMLParserDelegate,NSURLConnectionDataDelegate>

{

    NSMutableArray *classes;//类别

    NSMutableString *currentString;//当前字符

    NSMutableDictionary *currentFields;//当前字段

    NSDateFormatter * dateFormatter;//日期格式

    

    ScheduleFetcherResultBlock resultBlock;//创建块对象

    NSMutableData *responseData;//返回数据

    NSURLConnection *connection;//连接请求

    id<MyProtocol> myDelegate;

}


@property (strong) id<MyProtocol> myDelegate;

-(void)fetchClassesWithBlock:(ScheduleFetcherResultBlock)theBlock;

//如果成功则返回一个NSArray,失败则返回nil

-(NSArray*)fetchClassesWithError:(NSError**) outError;


@end


ScheduledFetcher.m

#import "ScheduleFetcher.h"

#import "ScheduledClass.h"

#import "AppDelegate.h"


@implementation ScheduleFetcher

@synthesize myDelegate;


- (instancetype)init

{

    self = [superinit];

    if (self) {

        myDelegate = [[AppDelegatealloc]init];

        classes = [[NSMutableArrayalloc]init];

        dateFormatter = [[NSDateFormatteralloc]init];

        //设置日期格式

        [dateFormattersetDateFormat:@"yyyy-MM-dd HH:mm:ss zzzz"];

    }

    return self;

}


-(void)fetchClassesWithBlock:(ScheduleFetcherResultBlock)theBlock{

    //复制块,保证其并不知存在栈中

    resultBlock = [theBlock copy];

    NSURL *xmlURL= [NSURLURLWithString:@"http://www.baidu.com/"];

    NSURLRequest *req = [NSURLRequestrequestWithURL:xmlURL cachePolicy:NSURLRequestReturnCacheDataElseLoadtimeoutInterval:30];

    connection = [[NSURLConnectionalloc]initWithRequest:reqdelegate:self];

    if (connection) {

        responseData = [[NSMutableDataalloc]init];

    }

    

}


-(void)cleanup{

    responseData = nil;

    connection = nil;

    resultBlock = nil;

}


#pragma mark-

#pragma mark NSURLConnection Delegate


//添加数据

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [responseData appendData:data];

}

//解析数据

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    [classesremoveAllObjects];

    NSXMLParser *parser = [[NSXMLParseralloc]initWithData:responseData];

    [parser setDelegate:self];

    BOOL success =[parser parse];

    if (!success) {

        resultBlock(nil,[parserparserError]);

    }else{

        NSArray*output = [classescopy];

        resultBlock(output,nil);

    }

    [self cleanup];

}

//连接失败

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    resultBlock(nil,error);

    [self cleanup];

}


//如果成功则返回一个NSArray,失败则返回nil

-(NSArray*)fetchClassesWithError:(NSError**) outError{

    

    BOOL success;

    //@"http://bignerdranch.com/xml/schedule"

    //1 NURL 设置访问地址

    NSURL *xmlURL= [NSURLURLWithString:@"http://www.baidu.com/"];

    //2 NSURLRequest 请求,缓存策略,超时

    NSURLRequest *request = [NSURLRequestrequestWithURL:xmlURL cachePolicy:NSURLRequestReturnCacheDataElseLoadtimeoutInterval:30];

    

    NSURLResponse *resp = nil;

    //3 NSURLConnection执行连接

    NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:&resp error:outError];

    

    if (!data) {

        return nil;

        [myDelegatecontent:nil forError:*outError];

    }

    

    [classesremoveAllObjects];

    

    //开始解析

    NSXMLParser *parser;

    parser = [[NSXMLParser alloc]initWithData:data];

    

    [parser setDelegate:self];//设置委托

    

    success = [parser parse];//解析是否成功

    if (!success) {

        *outError = [parser parserError];

        [myDelegate content:nil forError:*outError];

        return nil;

    }

    

    NSArray *output = [classescopy];

    [myDelegate content:output forError:nil];

    return output;

    

    // NSLog(@"Received %ld bytes",[data length]);

    

    // return nil;

}


#pragma mark-

#pragma mark NSXMLParserDelegate Methods

//元素的标记开始

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict{

    

    if ([elementName isEqual:@"class"]) {

        currentFields =[[NSMutableDictionaryalloc]init];

    }else if([elementNameisEqual:@"offering"]){

        [currentFields setObject:[attributeDict objectForKey:@"href"]forKey:@"href"];

    }

    

}

//元素的标记结束

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

    if([elementName isEqual:@"class"]){

        ScheduledClass *currentClass = [[ScheduledClassalloc]init];

        [currentClass setName:[currentFieldsobjectForKey:@"offering"]];

        [currentClass setLocation:[currentFieldsobjectForKey:@"location"]];

        [currentClass setHref:[currentFieldsobjectForKey:@"href"]];

        

        NSString *beginString = [currentFieldsobjectForKey:@"begin"];

        

        NSDate *beginDate = [dateFormatterdateFromString:beginString];

        [currentClass setBegin:beginDate];

        currentClass = nil;

        currentFields = nil;

        

    }elseif(currentFields&&currentString){

        NSString *trimmed;

        trimmed = [currentStringstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]];

        [currentFields setObject:trimmed forKey:elementName];

    }

    currentString = nil;

    

}


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

    

    if (!currentString) {

        currentString = [[NSMutableStringalloc]init];

    }

    [currentString appendString:string];

}

@end



MyProtocol.h

#import <Foundation/Foundation.h>


@protocol MyProtocol <NSObject>

-(void)content:(NSArray*)myClasses forError:(NSError*)error;

@end