博客> MKChained
MKChained
2018-11-08 09:56 评论:0 阅读:421 二日三点
ios 链式语法

MKChained

项目介绍

链式语法公开库

软件架构

MKChainedClass 需要继承的链式语法类 MKChainedPropertyClass 动态赋值类 MKChainedClassConst 原数据类 MKChainedClassError 报错类

安装教程

pod 'MKChained', :git => 'https://github.com/jxcz94754/MKChained.git'

使用说明

version-0.0.3

本次更新了一些报错的方式和字典方式的参数注入 例子

//1.链式写法
User *user = (User *)[[User alloc] init].intParamsWithDictionary(@{@"userId":@"10034",@"userName":@"厉害了",@"userAge":@"18",@"userSex":@"女"});

NSLog(@"username: %@ usersex : %@",user.userName,user.userSex);

其中新增了字典中key和Value是否和数据模型匹配 使用方式 在本类继承的过程中 在 .m文件中实现一个bool方法 此方法来判断是否允许空值的存在 也兼顾了类型判断

#import "User.h"

@implementation User

- (BOOL)propertyAllowEmpty {
return NO;
}
@end

直接继承MKChainedClass 使用initParamsWithArray 传入参数数组

#import <Foundation>
#import "MKChainedClass.h"

@interface User : MKChainedClass

@property (copy, nonatomic) NSString *userId;

@property (copy, nonatomic) NSString *userName;

@property (copy, nonatomic) NSString *userAge;

@property (copy, nonatomic) NSString *userSex;

@end
#import <Foundation>
#import "MKChainedClass.h"

@interface Focus : MKChainedClass

@property (assign, nonatomic) int type;

@property (strong, nonatomic) NSString *imageUrl;

@end

@interface FocusList : MKChainedClass

@property (strong, nonatomic) NSArray<Focus> *list;

@end
User *user = (User *)[[User alloc] init].initParamsWithArray(@[@(1),@"张三",@"18",@"女"]);

NSLog(@"user.username : %@ user.userid : %@",user.userName,user.userId);
Focus *focus = (Focus *)[[Focus alloc] init].initParamsWithArray(@[@100,@"123123123"]);

FocusList *list = (FocusList *)[[FocusList alloc] init].initParamsWithArray(@[@[focus]]);

NSLog(@"FocusList.focus.imageUrl : %@",[list.list[0] valueForKeyPath:@"imageUrl"]);
NSLog(@"FocusList.focus.type : %d",[[list.list[0] valueForKeyPath:@"type"] intValue]);

报错说明

[NSString stringWithFormat:@"errorcode : 1004 , %@ : %@ <- %@",propertyName,correctType,errorType];

其中propertyName为属性名称 correctType为正确的属性类型 errorType为错误的赋值类型

MKChainedClass 本类主要是给需要的NSobject类继承使用 主要进行了链式语法的转化 和 对数据源的数量和规格判断

#import <Foundation>
#import <objc>
#import "MKChainedPropertyClass.h"

@interface MKChainedClass : MKChainedPropertyClass

#pragma mark - SubClass - Version_0.0.1

/**
Chain assignment Will be divided into two forms A is a form of array (recommended) in the form of another way to use a dictionary

链式赋值 共分为两种形式 一种是数组的形式(推荐) 另外一种使用字典的形式*/

/**
数组形式的链式赋值
*/
@property (copy, nonatomic) MKChainedClass *(^initParamsWithArray)(NSArray *params);

/**
字典形式的链式赋值
*/
@property (copy, nonatomic) MKChainedClass *(^intParamsWithDictionary)(NSDictionary *params);

/**
是否允许属性值为空

@return 是否
*/
- (BOOL)propertyAllowEmpty;

@end
#import "MKChainedClass.h"
#import "MKChainedClassError.h"

@interface MKChainedClass()

@end

@implementation MKChainedClass

#pragma mark - ChainedMethond

- (MKChainedClass *(^)(NSArray*))initParamsWithArray {
    return ^MKChainedClass *(NSArray *params) {
        [self setAllPropertiesWithArray:params];
        return self;
    };
}

- (MKChainedClass *(^)(NSDictionary *))intParamsWithDictionary {
    return ^MKChainedClass *(NSDictionary *params) {
        [self setAllPropertiesWithDictionary:params];
        return self;
    };
}

#pragma mark - setValueMethond

- (void)setAllPropertiesWithArray:(NSArray *)params{

    u_int count;//属性的数量

    //获取属性名称
    objc_property_t *properties  =class_copyPropertyList([self class], &count);

    //是否允许空值的存在
    BOOL propertyAllowEmpty = [self propertyAllowEmpty];

    //当允许空值存在的时候
    if (propertyAllowEmpty == YES) {

        //当传入的值小于属性数量的时候
        if (params.count < count>= count) {

            [self setValueWithCount:params.count WithParams:params withProperties:properties];

        }
    }

    //当不允许空值存在的时候
    if (propertyAllowEmpty == NO) {

        //如果传入的值和属性数量不一致的时候
        if (params.count != count) {

                return [MKChainedClassError showErrorWithMKChainedClassErrorType:MKChainedClassErrorCrossing];

        }else{
            //当传入一致的时候
                [self setValueWithCount:params.count WithParams:params withProperties:properties];
        }
    }

    free(properties);
}

- (void)setAllPropertiesWithDictionary:(NSDictionary *)params {
    u_int count;//属性的数量

    //获取属性名称
    objc_property_t *properties  = class_copyPropertyList([self class], &count);

    //是否允许空值的存在
    BOOL propertyAllowEmpty = [self propertyAllowEmpty];

    //当允许空值存在的时候
    if (propertyAllowEmpty == YES) {

        //当传入的值小于属性数量的时候
        if (params.count < count>= count) {
            [self setValueWithCount:count WithDictionaryParams:params withProperties:properties];
        }
    }

    //当不允许空值存在的时候
    if (propertyAllowEmpty == NO) {

        //如果传入的值和属性数量不一致的时候
        if (params.count != count) {

            return [MKChainedClassError showErrorWithMKChainedClassErrorType:MKChainedClassErrorInvalid];

        }else{
        //当传入一致的时候
            [self setValueWithCount:count WithDictionaryParams:params withProperties:properties];

        }
    }
        free(properties);
}

- (BOOL)propertyAllowEmpty {
    return YES;
}

@end

MKChainedPropertyClass 本类主要是给返回的类进行动态赋值操作

MKChainedCheckPropertyClass 本类主要是给对传入的参数进行判断和甄选

#import <Foundation>
#import <objc>
#import "MKChainedClassConst.h"
#import "MKChainedClassError.h"

//数据源类型
typedef NS_ENUM(NSUInteger, MKChainedParamsType) {
MKChainedParamsString = 100,             // String
MKChainedParamsNumber = 101,             // Number
MKChainedParamsArray = 102,              // Array
MKChainedParamsModel = 103,              // Model
};

@interface MKChainedPropertyClass : NSObject

@property (assign, nonatomic) MKChainedParamsType chainedParamsType; //参数的类型

//根据不同的方式来进行数据赋值

- (void)setValueWithCount:(NSUInteger)count WithParams:(NSArray *_Nullable)params withProperties:(objc_property_t _Nullable *_Nullable)properties;

- (void)setValueWithCount:(NSUInteger)count WithDictionaryParams:(NSDictionary *_Nullable)params withProperties:(objc_property_t _Nullable *_Nullable)properties;

@end

//对参数params内的数据进行判断的类
@interface MKChainedCheckPropertyClass : MKChainedPropertyClass

//显示获取当前类的属性类型
+ (NSString *_Nullable)PropertiesName:(const char * _Nullable)property_Attributes;

//获取数组内元素的类型
+ (NSString *_Nullable)ParamsItemsName:(id _Nullable )paramsItems;

//检查赋值与被赋值的属性是否一致
+ (BOOL)checkNODifferenceWithPropertyName:(NSString * _Nullable )propertyName
                           WithParamsName:(NSString *_Nullable)paramsName
                              AndProperty:(NSString *_Nullable)property;

//获取错误类型
+ (MKChainedClassErrorType)getMKChainedClassError;

@end
#import "MKChainedPropertyClass.h"

@implementation MKChainedPropertyClass

- (void)setValueWithCount:(NSUInteger)count WithParams:(NSArray *)params withProperties:(objc_property_t *)properties{

    for (int i = 0; i < count xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed>= 'a' && dest_str[i] <= 'z') || (dest_str[i] >= 'A' && dest_str[i] <= 'Z')) {
        realType[j++] = dest_str[i];
        }
    }
    property_data_type = [NSString stringWithFormat:@"%s", realType];
    free(realType);

    }else {
        //Otherwise, take the second subscript character for comparing to the @encode()
        char * realType = [self getPropertyRealType:property_Attributes];
        property_data_type = [NSString stringWithFormat:@"%s", realType];
    }
    return property_data_type;
}

+ (NSString *_Nullable)ParamsItemsName:(id _Nullable )paramsItems {
    if ([paramsItems isKindOfClass:[NSString class]]) {

        return MKCLHAINEDCLASS_PROPERTY_TYPE_NSSRTING;
    }

    if ([paramsItems isKindOfClass:[NSArray class]]) {

        return MKCLHAINEDCLASS_PROPERTY_TYPE_NSSARRAY;
    }

    if ([paramsItems isKindOfClass:[NSNumber class]]) {

        return MKCLHAINEDCLASS_PROPERTY_TYPE_NSNUMBER;
    }

    return @"";
}

//检查赋值与被赋值的属性是否一致
+ (BOOL)checkNODifferenceWithPropertyName:(NSString *_Nullable)propertyName
                            WithParamsName:(NSString *_Nullable)paramsName
                            AndProperty:(NSString *_Nullable)property{

    if ([propertyName isEqualToString:paramsName]) {
        return YES;

    }else if ([paramsName isEqualToString:MKCLHAINEDCLASS_PROPERTY_TYPE_NSNUMBER] && [[MKChainedCheckPropertyClass basePropertyList] indexOfObject:propertyName] != NSNotFound) {
        //如果数组中的对象为number的时候
        return YES;
    }else{
        [MKChainedClassError showErrrorPropertyName:property ErrorParamsProperty:paramsName CorrectParamsName:propertyName];
        return NO;
    }
}

//获取错误类型
+ (MKChainedClassErrorType)getMKChainedClassError {
// TO DO
    return 1;
}

//其他的类型判断
+ (char *)getPropertyRealType:(const char * _Nullable)property_Attributes {

    if (MKChainedClass_Compare(property_Attributes[1], @encode(int))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_INT;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(char))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_CHAR;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(short))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_SHORT;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(long))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_LONG;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(unsigned char))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDCHAR;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(unsigned int))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDINT;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(unsigned short))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDSHORT;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(unsigned long))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDLONG;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(float))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_FLOAT;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(double))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_DOUBLE;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(_Bool))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_BOOL;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(bool))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_BOOL;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(void))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_VOID;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(char *))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_CHARALL;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(id))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_ID;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(Class))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_CLASS;}

    if (MKChainedClass_Compare(property_Attributes[1], @encode(SEL))) {return MKCLHAINEDCLASS_PROPERTY_TYPE_SEL;}

    return "";
}

+ (NSArray *)basePropertyList {
    return @[[NSString stringWithFormat:@"%s",MKCLHAINEDCLASS_PROPERTY_TYPE_INT],
            [NSString stringWithFormat:@"%s",MKCLHAINEDCLASS_PROPERTY_TYPE_FLOAT],
            [NSString stringWithFormat:@"%s",MKCLHAINEDCLASS_PROPERTY_TYPE_DOUBLE],
            [NSString stringWithFormat:@"%s",MKCLHAINEDCLASS_PROPERTY_TYPE_LONG],
            [NSString stringWithFormat:@"%s",MKCLHAINEDCLASS_PROPERTY_TYPE_BOOL]];
}

@end

MKChainedClassError 本类主要是对错误类型进行了处理 show了一些错误的message方便程序调试

#import <Foundation>

/*
This class contains the type of error, error of arrays and dictionaries in it.Generally includes dictionary keys do not conform with the properties of the data model, the dictionary has a value of null values.The number of array and attribute quantity does not meet.The preaching of objects are neither an array or dictionary

本类中包含的错误类型,数组和字典的错误在其中。一般包括字典键与数据模型的属性不相符合,字典的值为空值。数组的数量和属性数量不相符合。所传的对象既不是数组也不是字典
*/

typedef NS_ENUM(NSUInteger, MKChainedClassErrorType) {
    MKChainedClassErrorKey = 1001,             // key error
    MKChainedClassErrorValue = 1002,           // value error
    MKChainedClassErrorCrossing = 1003,        // arrray error
    MKChainedClassErrorInvalid = 1004          // object error
};

@interface MKChainedClassError : NSObject

@property (assign, nonatomic) MKChainedClassErrorType classErrorType; //MKChainedClassErrorType

+ (void)showErrorWithMKChainedClassErrorType:(MKChainedClassErrorType)classErrorType; //show NSLog with MKChainedClassErrorType

/**
显示错误的类型名字

@param propertyName 属性名称
@param errorType 错误的属性
@param correctType 正确的属性
*/
+ (void)showErrrorPropertyName:(NSString *)propertyName
ErrorParamsProperty:(NSString *)errorType
CorrectParamsName:(NSString *)correctType;

@end
#import "MKChainedClassError.h"

@implementation MKChainedClassError

#pragma mark - setter

- (void)setClassErrorType:(MKChainedClassErrorType)classErrorType {
switch (classErrorType) {
    case MKChainedClassErrorKey:
    {
        NSLog(@"The key of errors exist in the dictionary");
    }
    break;
    case MKChainedClassErrorValue:
    {
        NSLog(@"The value of errors exist in the dictionary");
    }
    break;
    case MKChainedClassErrorCrossing:
    {
        NSLog(@"Quantity does not conform to the array and the number of attributes");
    }
    break;
    case MKChainedClassErrorInvalid:
    {
        NSLog(@"Initialization of the parameters is not correct");
    }
    break;
    default:
    {
        NSLog(@"An unknown error");
    }
    break;
    }
}

+ (void)showErrorWithMKChainedClassErrorType:(MKChainedClassErrorType)classErrorType {
    switch (classErrorType) {
    case MKChainedClassErrorKey:
    {
        NSLog(@"The key of errors exist in the dictionary");
    }
    break;
    case MKChainedClassErrorValue:
    {
        NSLog(@"The value of errors exist in the dictionary");
    }
    break;
    case MKChainedClassErrorCrossing:
    {
        NSLog(@"Quantity does not conform to the array and the number of attributes");
    }
    break;
    case MKChainedClassErrorInvalid:
    {
        NSLog(@"Initialization of the parameters is not correct");
    }
    break;
    default:
    {
        NSLog(@"An unknown error");
    }
    break;
    }
}

+ (void)showErrrorPropertyName:(NSString *)propertyName
            ErrorParamsProperty:(NSString *)errorType
            CorrectParamsName:(NSString *)correctType {
    NSString *errorMessage = [NSString stringWithFormat:@"errorcode : 1004 , %@ : %@ <-  %@",propertyName,correctType,errorType];
    NSAssert([errorType isEqualToString:correctType], errorMessage);
}

错误在后台的显示

当前传入的Params为字典的时候 key值没有找到

 56ECC641-0D29-42EB-B312-834A26FEAB8F.png

value值类型不匹配

 82A03315-AEF3-4394-879A-CAE918AC0F2C.png

在不允许空值的情况下 字典参数数量不正确

 8FDA583C-8D11-4AE0-81D7-622C300FC701.png

MKChainedClassConst 本类对原数据进行了设置

#import <Foundation>
#import <UIKit>

//传入参数的数据类型
UIKIT_EXTERN NSString * const  MKCLHAINEDCLASS_PROPERTY_TYPE_NSSRTING;
UIKIT_EXTERN NSString * const  MKCLHAINEDCLASS_PROPERTY_TYPE_NSSARRAY;
UIKIT_EXTERN NSString * const  MKCLHAINEDCLASS_PROPERTY_TYPE_NSNUMBER;
UIKIT_EXTERN NSString * const  MKCLHAINEDCLASS_PROPERTY_TYPE_MODEL;

//传入参数对象或者数组内的元素的类型(基本类型)

UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_INT;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_CHAR;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_SHORT;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_LONG;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDCHAR;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDINT;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDSHORT;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDLONG;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_FLOAT;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_DOUBLE;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_BOOL;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_VOID;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_CHARALL;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_ID;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_CLASS;
UIKIT_EXTERN char *   MKCLHAINEDCLASS_PROPERTY_TYPE_SEL;

//字符串的比较
#define MKChainedClass_Compare(currentString,compareString) [[NSString stringWithFormat:@"%c",currentString] isEqualToString:[NSString stringWithFormat:@"%s",compareString]]

@interface MKChainedClassConst : NSObject

@end
#import "MKChainedClassConst.h"

//判断字符串相等的宏方法

//#define MKChained_StringCompare(currentString,compareString,resultString,defaultString) (if ([currentString isEqualToString:compareString]) { return resultString;})

@implementation MKChainedClassConst

NSString * const  MKCLHAINEDCLASS_PROPERTY_TYPE_NSSRTING = @"NSString";
NSString * const  MKCLHAINEDCLASS_PROPERTY_TYPE_NSSARRAY = @"NSArray";
NSString * const  MKCLHAINEDCLASS_PROPERTY_TYPE_NSNUMBER = @"NSNumber";
NSString * const  MKCLHAINEDCLASS_PROPERTY_TYPE_MODEL = @"MODEL";

char *   MKCLHAINEDCLASS_PROPERTY_TYPE_INT = "int";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_CHAR = "char";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_SHORT = "short";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_LONG = "long";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDCHAR = "unsigned char";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDINT = "unsigned int";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDSHORT = "unsigned short";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_UNSIGNEDLONG = "unsigned long";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_FLOAT = "float";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_DOUBLE = "double";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_BOOL = "BOOL";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_VOID = "void";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_CHARALL = "char *";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_ID = "id";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_CLASS = "Class";
char *   MKCLHAINEDCLASS_PROPERTY_TYPE_SEL = "SEL";

@end

代码下载地址 : https://gitee.com/huangyangyang/MKChained

下一篇 : 链式语法开源库 MKUIChained 地址: http://blog.cocoachina.com/article/70632

收藏
0
sina weixin mail 回到顶部