iOS中block的定义及使用

1、定义

2、使用示例

(1)Downloader.h

#import <Foundation/Foundation.h>

typedef void (^SOLWeatherDataDownloadCompletion)(NSDictionary *dic, NSError *error);

@interface Downloader : NSObject

+ (instancetype)sharedDownloader;
- (void)dataForUrl:(NSString *)requestURL completion:(SOLWeatherDataDownloadCompletion)completion;

@end

(2)Downloader.m

#import "Downloader.h"

@implementation Downloader

static Downloader *_sharedDownloader = nil;

+ (instancetype)sharedDownloader {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedDownloader = [[super allocWithZone:NULL] init];
    });
    
    return _sharedDownloader;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    return [Downloader sharedDownloader];
}

- (id)copyWithZone:(struct _NSZone *)zone {
    return [Downloader sharedDownloader];
}

- (void)dataForUrl:(NSString *)requestURL completion:(SOLWeatherDataDownloadCompletion)completion {
    if(!requestURL || !completion)
        return;
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
     ^ (NSURLResponse *response, NSData *data, NSError *connectionError) {
         if(connectionError)
             completion(nil, connectionError);
         else {
             @try {
                 NSError *JSONSerializationError;
                 NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&JSONSerializationError];
                 completion(JSON, connectionError);
             }
             @catch (NSException *exception) {
                 completion(nil, [NSError errorWithDomain:@"Downloader Internal State Error" code:-1 userInfo:nil]);
             }
             @finally {
                 
             }
         }
     }];
}

@end

(3)调用示例

static NSString *baseURL =  @"http://api.wunderground.com/api/";
static NSString *parameters = @"/forecast/conditions/q/";
static NSString *APIKey = @"0def10027afaebb7";
NSString *requestURL = [NSString stringWithFormat:@"%@%@%@%f,%f.json", baseURL, APIKey, parameters, 39.897445, 116.331398];
[[Downloader sharedDownloader] dataForUrl:requestURL completion:^(NSDictionary *dic, NSError *error) {
    if (dic)
        NSLog(@"%@",dic);
}];

猜你喜欢

转载自eric-gao.iteye.com/blog/2213834