尝试过以下几种方式都不太理想:
-
不对接口名作定义,直接编写字符串
缺点:没有统一管理的地方,接口值散落,同一接口多处使用时不易维护,易拼写错误;接口值作为数据资源不应直接混入逻辑代码中
NSString *urlString = [NSString stringWithFormat:@"%@%@", @"http://www.baidu.com/", @"app/login"];
-
宏定义接口名
缺点:接口各自定义,没有形成集合或类型。在把接口作为参数传值时,只能以字符串为类型接收。
#define ServerHost @"http://www.baidu.com/"
#define ServerApiLogin @"app/login"
NSString *urlString = [NSString stringWithFormat:@"%@%@", ServerHost, ServerApiLogin];
-
用枚举定义接口名+plist文件映射存储接口字符串
缺点:枚举值是整型,导致接口多了顺序属性,顺序或者说索引并不是接口应该含有需要的东西,反而会成为累赘,不利于接口集的增删插入
// ServerApi.plst存储了接口字符串数组
NSURL *url = [[NSBundle mainBundle] URLForResource:@"ServerApi" withExtension:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfURL:url];
NSString *api = array[ServerApi];
NSString *urlString = [NSString stringWithFormat:@"%@%@", ServerHost, api];
使用字符串常量+类型定义
这是参考苹果API的定义方式
//
// JXRequester.h
//
#import <UIKit/UIKit.h>
typedef NSString * ServerApi;
UIKIT_EXTERN ServerApi const ServerApiLogin;
UIKIT_EXTERN ServerApi const ServerApiRegister;
UIKIT_EXTERN ServerApi const ServerApiBannerList;
@interface JXRequester : NSObject
+ (void)postApi:(ServerApi)api params:(NSDictionary *)params completion:(void (^)())completion;
@end
//
// JXRequester.m
//
#import "JXRequester.h"
NSString * const ServerHost = @"http://www.baidu.com/";
ServerApi const ServerApiLogin = @"app/ServerApiLogin";
ServerApi const ServerApiRegister = @"app/ServerApiRegister";
ServerApi const ServerApiBannerList = @"app/ServerApiBannerList";
@implementation JXRequester
+ (void)postApi:(ServerApi)api params:(NSDictionary *)params completion:(void (^)())completion {
NSString *urlString = [NSString stringWithFormat:@"%@%@", ServerHost, api];
}
@end
//
// ViewController.m
//
#import "ViewController.h"
#import "JXRequester.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self onLoginButton];
}
#pragma mark - 登录
- (void)onLoginButton {
NSDictionary *parms = @{@"username" : @"jiongxing",
@"password" : @"123456"};
[JXRequester postApi:ServerApiLogin params:parms completion:^{
}];
}
若有更好思路欢迎留言 ^^
网友评论