iOS UI 17 初级数据持久化
//
// Network.m
// UI - 15网络编程
//
// Created by dllo on 15/11/30.
// Copyright (c) 2015年 dllo. All rights reserved.
//
#import "Network.h"
@implementation Network
+ (void)getDataSyWithURLStr:(NSString *)urlstr block:(void (^)(NSData *))block
{
//6, IOS9.0后使用的未明字符转换,未明字符如中文
NSString *urlEncode = [urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//4,创建url
NSURL *url = [NSURL URLWithString:urlEncode];
//3,创建请求对象,request可设置信息如:url,方式(GET/POST),超时时间等
// NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:60 ];
//1,创建NSURLSession对象,选择默认配置
NSURLSession *sessioin = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//2 ,创建请求任务,当异步请求完成会调用block,在block里面完成数据处理
NSURLSessionDataTask * getTast = [sessioin dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
block(data);
//当数据请求完毕,在此处解析数据
// NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
// NSLog(@"%@",dic);
/**
* 注意刷新界面 [self.tablev releaload]
*/
}];
//7, 开始任务
[getTast resume];
}
@end
//
// Student.h
// UI - 17 初级数据持久化
//
// Created by dllo on 15/12/1.
// Copyright (c) 2015年 dllo. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface Student : NSObject <NSCoding>
@property (nonatomic ,copy)NSString *name;
@property (nonatomic ,copy)NSString *sex;
@property (nonatomic ,assign)NSInteger num;
@property (nonatomic ,assign) CGFloat score;
@end
//
// Student.m
// UI - 17 初级数据持久化
//
// Created by dllo on 15/12/1.
// Copyright (c) 2015年 dllo. All rights reserved.
//
#import "Student.h"
@implementation Student
- (void)dealloc
{
[_name release];
[_sex release];
[super dealloc];
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
// 使复杂对象实现NSCoding协议
//对Student对象进行归档时,此方法执行。
//对Student中想要进行归档的所有属性,进行编码操作
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.sex forKey:@"sex"];
//key 值不一定很属性同名 只为了在反归档时能够找到对应上就可以
[aCoder encodeInteger:self.num forKey:@"学号"];
[aCoder encodeDouble:self.score forKey:@"分数"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
// 对person对象进行反归档时,该方法执行
//创建一个新的person对象,所有属性都是通过解码得到的
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.sex = [aDecoder decodeObjectForKey:@"sex"];
self.num = [aDecoder decodeIntegerForKey:@"学号"];
self.score = [aDecoder decodeDoubleForKey:@"分数"];
}
return self;
}
@end