1.下面代码来自一个tableView的demo,该demo的数据来源于mainBundle的plist文件
tgs是tableViewController的属性
/**
* 数据的懒加载
*/
- (NSMutableArray *)tgs
{
if (_tgs == nil) {
// 1.获取plist文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"tgs.plist" ofType:nil];
// 2.加载数组
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
// 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
NSMutableArray *tgArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
// 3.1.创建模型对象
MJTg *tg = [MJTg tgWithDict:dict];
// 3.2.添加模型对象到数组中
[tgArray addObject:tg];
}
_tgs = tgArray;
}
return _tgs;
}
2.1把mac的php,apache配置并启动.配置方法百度上有.
修改mainBundle里的tgs.plist文件,改为tgs.xml,然后把文件放到locahost本地路径.用火狐打开http://localhost/tgs.xml
2.2修改上面的代码段
/**
* 数据的懒加载
*/
- (NSMutableArray *)tgs
{
if (_tgs == nil) {
// 创建并行队列
dispatch_queue_t q = dispatch_queue_create("load data", DISPATCH_QUEUE_CONCURRENT);
// 创建异步任务
dispatch_async(q, ^{
// 1.获取网络路径
NSURL *url = [NSURL URLWithString:@"http://localhost/tgs.xml"];
// 2.加载数组
NSArray *dictArray = [NSArray arrayWithContentsOfURL:url];
// 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
NSMutableArray *tgArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
// 3.1.创建模型对象
MJTg *tg = [MJTg tgWithDict:dict];
// 3.2.添加模型对象到数组中
[tgArray addObject:tg];
}
dispatch_async(dispatch_get_main_queue(), ^{
self.tgs = tgArray;
});
});
}
return _tgs;
}
/**
* 数据的懒加载
*/
- (NSMutableArray *)tgs
{
if (_tgs == nil) {
// 获取网络url
NSURL *url = [NSURL URLWithString:@"http://localhost/tgs.xml"];
// 创建请求
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10.0f];
// 发起请求
[NSURLConnection sendAsynchronousRequest:requestURL queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 1.缓存至本地
NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *path = [cache stringByAppendingPathComponent:@"tgs.plist"];
[data writeToFile:path atomically:YES];
// 2.加载数组
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
// 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
NSMutableArray *tgArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
// 3.1.创建模型对象
MJTg *tg = [MJTg tgWithDict:dict];
// 3.2.添加模型对象到数组中
[tgArray addObject:tg];
}
dispatch_async(dispatch_get_main_queue(), ^{
self.tgs = tgArray;
});
}];
}
return _tgs;
}
代码后续补充