iOS代码规范

1.网络层:
@interface WM_NetworkManager : AFHTTPSessionManager

单例:+(WM_NetworkManager *)shareInstance
{
static WM_NetworkManager * shareInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
shareInstance = [[self alloc] init];
});
return shareInstance;
}

  • (instancetype)init
    {
    if (self = [super init]) {
    [self Reachability];
    [self setSessionManagerParameter];
    }
    return self;
    }

pragma mark -- 网络监听

  • (void)Reachability
    {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    //debugLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
    }];

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    }
    AFHTTPSessionManager:

  • (void)setSessionManagerParameter
    {
    //设置请求头参数
    _sessionManager = [AFHTTPSessionManager manager];
    _sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    _sessionManager.requestSerializer.timeoutInterval = 20;
    _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    [_sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    }
    实例方法:

pragma mark 数据请求封装

-(void)postPath:(NSString *)path parameters:(NSDictionary *)parameters withBlock:(void (^)(NSDictionary *, NSError *))block
{

NSString * url = [[WM_Single defaultSingle].APIHOST stringByAppendingString:path];

// NSString * url = @"http://192.168.2.165:8888/WebMobile.asmx/GetDepartByUserId";
[_sessionManager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
debugLog(@"成功");
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (block) {
//NSLog(@"responseObject:%@",responseObject);
if (![[responseObject objectForKey:@"msg"] isEqualToString:@"ok"]) {
NSError *error = [NSError errorWithDomain:@"Message" code:[[responseObject objectForKey:@"ErrCode"] intValue] userInfo:[NSDictionary dictionaryWithDictionary:responseObject]];
block(nil,error);
// debugLog(@"%@", responseObject);
}else{
// NSString * str = [[WM_NetworkManager shareInstance] dictionaryToJson:responseObject];
block(responseObject,nil);
debugLog(@"请求成功");
// debugLog(@"responseObject11:%@", responseObject);
}
}
debugLog(@"%@", task);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
debugLog(@"%@", task);
debugLog(@"%@", error);
block(nil,error);

}];

}
//词典转换为字符串

  • (NSString*)dictionaryToJson:(NSDictionary *)dic
    {

    NSError *parseError = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

pragma mark - 将解析的数据转化成字典

-(NSMutableDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if (err) {
NSLog(@"解析失败");
return nil;
}
return dic;
}
//将解析的数据转化成数组
-(NSMutableArray *)arrayWithJsonString:(NSString *)jsonString
{
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if (err) {
NSLog(@"解析失败");
return nil;
}
return array;
}
2.网络层第二层:类方法
//根据登录人获得其有权限的仓库

  • (void)getDepartWithBlock:(void(^)(NSDictionary * result, NSError * error))block
    {
    NSString *userId = [[WM_Single defaultSingle] getTheValueOfUserName];
    NSDictionary * params = @{@"userId" : userId};
    [[WM_NetworkManager shareInstance] postPath:GetDepartURL parameters:params withBlock:block];
    }
    3.单例:保存到本地:
  • (WM_Single *)defaultSingle
    {
    static WM_Single * single;
    if (!single) {
    single = [[WM_Single alloc] init];
    }
    return single;
    }
    //将用户名存入本地
  • (void)setValueWithUserName:(NSString *)userName
    {
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    [ud setValue:userName forKey:@"userName"];
    [ud synchronize];
    }
    //从本地取得用户名

  • (NSString *)getTheValueOfUserName
    {
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    return [ud stringForKey:@"userName"];
    }
    4.属性懒加载:
    -(NSMutableArray *)comNameArray{
    if (!_comNameArray) {
    _comNameArray = [[NSMutableArray alloc]init];
    }
    return _comNameArray;
    }
    5.自动登录:记住密码
    6.找回密码功能
    7.用户配置功能:
    if ([[WM_Single defaultSingle]getTheValueOfAPI] == nil) {

          _textField.text = @"http://192.168.2.165:8888/WebMobile.asmx/";
      }else{
      
          _textField.text = [[WM_Single defaultSingle]getTheValueOfAPI];
      }
    

8.请求加载:
UIWindow* window = [UIApplication sharedApplication].keyWindow;
__weak MBProgressHUD *hud = [ShowMessage showLoadingData:window];
[hud hide:YES];
9.判断手机是否联网:
//判断手机是否联网
AFNetworkReachabilityManager *managerAF = [AFNetworkReachabilityManager sharedManager];
[managerAF startMonitoring];
[managerAF setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

  switch (status) {
      case AFNetworkReachabilityStatusUnknown:
          [ShowMessage showTextOnly:@"暂时没有网络,登录时请检查网络" messageView:self.view];
          wangluo = false;
          break;
          
      case AFNetworkReachabilityStatusNotReachable:
          
          [ShowMessage showTextOnly:@"暂时没有网络,登录时请检查网络" messageView:self.view];
          wangluo = false;
          break;
          
      default:
          wangluo = true;
          break;
  }

}];
10.点击view缩放键盘:

  • (void)tapView{

    UITapGestureRecognizer tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tap1.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap1];
    }
    -(void)viewTapped:(UITapGestureRecognizer
    )tap1
    {
    [self.view endEditing:YES];
    }

  1. 加载启动图片:在ViewController的viewDidLoad中
    if ([[WM_Single defaultSingle]getTheValueOfUserName]) {

    self.password.text = [[WM_Single defaultSingle]getTheValueOfPassword];
    self.userName.text = [[WM_Single defaultSingle]getTheValueOfUserName];
    self.OrganizeStructureTf.text = [[WM_Single defaultSingle]getValueOfComName];
    [WM_Single defaultSingle].APIHOST = @"http://192.168.2.165:8888/WebMobile.asmx/";
    
    UIImageView *startImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    _startImage = startImage;
    startImage.image = [UIImage imageNamed:@"云仓储启动页"];
    
    [self.view addSubview:startImage];
    [self LoginClick:nil];
    

    }
    11.设置占位符颜色:
    self.userName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor],NSFontAttributeName:[UIFont systemFontOfSize:16]}];
    12.输入框的监听来判断登录按钮的监听事件:
    //创建通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    _center = center;
    //注册通知
    [center addObserver:self selector:@selector(textValueChanged) name:UITextFieldTextDidChangeNotification object:self.userName];
    [center addObserver:self selector:@selector(textValueChanged) name:UITextFieldTextDidChangeNotification object:self.password];
    [center addObserver:self selector:@selector(textValueChanged) name:UITextFieldTextDidChangeNotification object:self.OrganizeStructureTf];

  • (void)textValueChanged
    {
    LoginButton.enabled = ((self.userName.text.length != 0) && (self.password.text.length != 0) && (self.OrganizeStructureTf.text.length != 0));
    if (LoginButton.enabled) {
    [LoginButton setImage:[UIImage imageNamed:@"登录1"] forState:UIControlStateNormal];
    }else{
    [LoginButton setImage:[UIImage imageNamed:@"登录2"] forState:UIControlStateNormal];
    }
    }
    千万一处通知:
    //移除通知
  • (void)dealloc
    {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    13.下拉框实现
    14.cellForRowAtIndexPath:

import "Masonry/Masonry.h"

//一些操作在cell中进行
PopupViewCell *cell = [PopupViewCell popupViewCellWithTableView:tableView];
cell.iconView.image = self.iconArray[indexPath.row];
cell.titleLable.text = self.textArray[indexPath.row];
//cell分割线
if (indexPath.row == self.textArray.count - 1) {
cell.haveSeparatorLine = YES;
}else{
cell.haveSeparatorLine = NO;
}
----------------cell-------------属性---------------

  • (instancetype)popupViewCellWithTableView:(UITableView *)tableView;

@property (nonatomic, strong) UIImageView *iconView;
@property (nonatomic, strong) UILabel *titleLable;

@property (nonatomic, assign, getter=isHaveSeparatorLine) BOOL haveSeparatorLine; //是否有分割线
----------------cell---------------------------------

  • (instancetype)popupViewCellWithTableView:(UITableView *)tableView {

    static NSString *cellID = @"PopupViewCell";

    PopupViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!cell) {
    cell = [[PopupViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    return cell;
    }

  • (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    if ( self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    self.selectionStyle = UITableViewCellSelectionStyleNone;

      self.iconView = [[UIImageView alloc] init];
      [self.contentView addSubview:self.iconView];
      
      self.titleLable = [[UILabel alloc] init];
      self.titleLable.textColor = [UIColor blackColor];
      self.titleLable.font = [UIFont systemFontOfSize:14];
      [self.contentView addSubview:self.titleLable];
      
      //添加分割线
      self.separatorLineView = [[UIImageView alloc] init];
      self.separatorLineView.backgroundColor = [UIColor grayColor];
      [self.contentView addSubview:self.separatorLineView];
    

// self.separatorLineView.hidden = YES;
}
return self;
}

  • (void)layoutSubviews{

    [super layoutSubviews];

    [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.contentView).offset(padding);
    make.centerY.equalTo(self.contentView);
    make.width.equalTo(@(0));
    make.height.equalTo(@(0));
    }];

    [self.titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.iconView.mas_trailing).offset(padding);
    make.centerY.equalTo(self.contentView);
    make.trailing.equalTo(self.contentView).offset(-padding);
    make.bottom.equalTo(self.contentView);
    }];

    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.textLabel);
    make.trailing.equalTo(self.contentView);
    make.bottom.equalTo(self.contentView.mas_bottom);
    make.height.equalTo(@(1 / ([UIScreen mainScreen].scale)));
    }];
    }

-(void)setHaveSeparatorLine:(BOOL)haveSeparatorLine{
_haveSeparatorLine = haveSeparatorLine;
self.separatorLineView.hidden = haveSeparatorLine;
}

你可能感兴趣的:(iOS代码规范)