创建一个数据请求的类 , 写个数据类协议
DateHelper.h #import <Foundation/Foundation.h> @protocol DateHelperDelegate<NSObject> - (void)DicFromURL:(NSDictionary *)dic; @end @interface DateHelper : NSObject @property (nonatomic ,assign) id <DateHelperDelegate> delegateDate; - (void )getDateFromURL:(NSString *)url; @end
.m 文件内实现 网络请求
- (void)getDateFromURL:(NSString *)url { NSString * urlString = url; NSString * newUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL * URL = [NSURL URLWithString:newUrlString]; NSURLRequest * request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; // NSLog(@"%@",dic); if ([self.delegateDate respondsToSelector:@selector(DicFromURL:)]) { [self.delegateDate DicFromURL:dic]; } }]; }
让需要数据的类服从协议 , 并实现方法 : 如果需要多个界面复用 . 我在- (void)viewWillAppear:(BOOL)animated: 中实现服从协议,并 传值.
- (void)viewWillAppear:(BOOL)animated { DateHelper * helper = [[DateHelper alloc]init]; [helper getDateFromURL:@"http://www.duitang.com/napi/ad/banner/week/" ]; helper.delegateDate = self; [helper release]; } - (void)DicFromURL:(NSDictionary *)dic { self.diction = dic; NSLog(@"HOME %@ HOME ",dic); }