版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
用manage封装一个请求类, 把网络请求写在manage里, 然后在model里完成数据解析
网络请求代码
- (void)postNowData:(successful)result {
NSString *str = [NSString stringWithFormat:@"%s/v2/movie/in_theaters", nowHttp];
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *nowDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
DBModel *allData = [[DBModel alloc] initWithDictionary:nowDictionary error:nil];
// DBNowModel *nowData = [[DBNowModel alloc] init];
// nowData = allData.subjects[0];
NSInteger i = [allData.subjects count];
result(allData, i);
} else {
NSLog(@"FALSE");
}
}];
[dataTask resume];
}
manage的创建使用单例模式
-
在iOS开发过程中,需要使用到一些全局变量以及管理方法,可以将这些变量以及方法封装在一个管理类中,这是符合MVC开发模式的,这就需要使用单例(singleton)。
-
使用单例模式的变量在整个程序中只需要创建一次,而它生命周期是在它被使用时创建一直到程序结束后进行释放的,类似于静态变量,所以我们需要考虑到它的生命周期,唯一性以及线程安全。在这里,我们需要实用GCD来实现单例模式:
(保证线程安全, 不能确定代码的执行顺序,线程是不安全的)
代码实现
+ (instancetype)sharedManger {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (manger == nil) {
manger = [[DBManger alloc] init];
}
});
return manger;
}
JSONModel实现数据解析, 写在Model里
代码实现
#import "JSONModel.h"
NS_ASSUME_NONNULL_BEGIN
//
//
@protocol DBNowModel
@end
@protocol DBSubjectModel
@end
@protocol RatingModel
@end
@protocol ImageModel
@end
@interface ImageModel : JSONModel
@property NSString* medium;
@end
@interface RatingModel : JSONModel
@property NSString* average;
@end
@interface DBNowModel : JSONModel
@property NSString* title;
@property RatingModel* rating;
@property ImageModel* images;
@end
@interface DBModel : JSONModel
@property NSArray<DBNowModel>* subjects;
@end