有一段时间没写博客了,太忙了最近,但是我还是尽量抽时间去完成自己的博客历程,哈哈,今天就说说在项目中常用的技巧之一:合理使用类的类别去优化自己的代码结构。
所谓合理,顾名思义就是根据自己的需要用合适的方案去解决一些代码重复问题。如果在项目开发中,我们大量的使用某个类的一些属性方法,此时我们不妨考虑一下使用类的类别来进行优化,这样会简化很多工作。
举个例子,我们在开发中,一定会去创建一些模型,来封装一些网络数据,每次都是重复的工作去设置对应的key与value,想想都烦(起码我是挺烦的),后来也算是找寻各种方案吧,最后还是觉得将这些属性值的设置封装在类中,并将其放在NSObject类别中是最方便的,使用的时候,直接去导入扩展,直接就能用了,岂不很好。好了,原理大概就这样,我们来去实现它:
先定义类别:
//
// NSObject+Model.h
// RoundCornersDemo
//
// Created by Lee on 15-11-9.
// Copyright (c) 2015年 Lee. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (Model)
+ (instancetype)objectForDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
//
// NSObject+Model.m
// RoundCornersDemo
//
// Created by Lee on 15-11-9.
// Copyright (c) 2015年 Lee. All rights reserved.
//
#import "NSObject+Model.h"
@implementation NSObject (Model)
+ (instancetype)objectForDict:(NSDictionary *)dict{
return [[self alloc]initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict{
if (self = [self init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
@end
同时我还设置了一个切圆角的扩展类方便切圆角
//
// UIView+RoundCorner.h
// RoundCornersDemo
//
// Created by Lee on 15-11-8.
// Copyright (c) 2015年 Lee. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIView (RoundCorner)
- (void)clipToRound:(CGFloat )cornerSize;
@end
//
// UIView+RoundCorner.m
// RoundCornersDemo
//
// Created by Lee on 15-11-8.
// Copyright (c) 2015年 Lee. All rights reserved.
//
#import "UIView+RoundCorner.h"
@implementation UIView (RoundCorner)
- (void)clipToRound:(CGFloat )cornerSize{
self.layer.cornerRadius = cornerSize;
self.clipsToBounds = YES;
}
@end
使用的时候我们只需要导入扩展头文件,然后就可以直接用了,如下
//
// ViewController.m
// RoundCornersDemo
//
// Created by Lee on 15-11-8.
// Copyright (c) 2015年 Lee. All rights reserved.
//
#import "ViewController.h"
#import "UIView+RoundCorner.h"
#import "NSObject+Model.h"
#import "TicketModel.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//切圆角
[self clipToRound];
//设置图形
[self createModel];
}
- (void)createModel{
//设置模型,此时的字典应该为网络请求以后获取的json数据字典,此时就设置为空了
NSDictionary *dic = nil;
//仅仅通过一句话,即可完成模型的赋值了
TicketModel *model = [TicketModel objectForDict:dic];
}
- (void)clipToRound{
[self.view setBackgroundColor:[UIColor redColor]];
[self.view clipToRound:100];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这种思想是不是挺方便的,哈哈,总之如果以后经常用到的一些方法,我们不妨将其封装在类的类别中,这样就很方便的进行使用了,尽管很简单,但是却大大提高了程序的简洁性。