我只是维持这个结构。
|view
|--all the .xib's and Storyboard
|Controller
|--All the View Controller both .h and .m file
|model
|--.h and .m file for each controller which would be call models.
例子。
|view
|--login.xib
|Controller
|--loginViewController.h
|--loginViewController.m
|model
|--loginModel.h
|--loginModel.m
在 LoginModel 中,我通常处理 API 调用并将所有 json 转换为对象 NSMutableDictionary 并将数据发送到控制器以进行进一步处理。
在 My loginController 中,它将对收到的数据执行操作。
示例:我正在使用 AFNetworking 进行 API 调用。
AFHTTPAPIClient.h
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
@interface AFHTTPAPIClient : AFHTTPClient
+ (AFHTTPAPIClient *)sharedClient;
@end
AFHTTPAPIClient.m
#import "AFHTTPAPIClient.h"
@implementation AFHTTPAPIClient
// Singleton Instance
+ (AFHTTPAPIClient *)sharedClient {
static AFHTTPAPIClient *sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedClient = [[AFHTTPAPIClient alloc] initWithBaseURL:[NSURL URLWithString:@"www.yourdomain.com"]];
});
return sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:@"Accept" value:@"application/json"];
return self;
}
@end
登录模型.h
#import "AFHTTPAPIClient.h"
+ (void)loginWith:(NSDictionary *)parameters withBlock:(void (^)(NSMutableDictionary *, NSError *))block;
登录模型.m
+ (void)loginWith:(NSDictionary *)parameters withBlock:(void (^)(NSMutableDictionary *, NSError *))block {
[[AFHTTPAPIClient sharedClient] postPath:@"/api/login" parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(@"%@",responseObject);
if (block) {
block(responseObject, nil);
}
}
failure:^(AFHTTPRequestOperation *operation,NSError *error){
if (block) {
block([NSArray array], error);
}
}];
}
然后最后在控制器中使用它们。
登录视图控制器.m
NSDictionary * loginParametes = [[NSDictionary alloc] initWithObjectsAndKeys:_txtUsername.text,@"username", _txtPassword.text,@"password",nil];
[LoginModel loginWith:loginParametes withBlock:^(NSMutableDictionary *loginInfo, NSError *error) {
if (!error) {
if([[loginInfo objectForKey:@"status"] boolValue]==YES){
// Login Success
}
else {
// Login Failure
}
}
else {
// API Responce failure if content type is not a valid json or valid status code.
}
}];