Fault Tolerance in iOS development -- YRClassSafeCategory
YRClassSafeCategory
Recently, I found that many of my friends are asking me how to solve the fault tolerance problem during similar parsing. After thinking about it, I just open-source the small fault tolerance library I 've been using a few years ago.
During iOS development, you often encounter dictionary resolution or other conversions, such as the following dictionary:
NSDictionary *dictionary = @{@"num1":@1, @"num2":@"2", @"string":@"this is a string", @"dic":@{@"key":@"value"}, @"array":@[@1,@2], };
General Parsing
-(Void) parseDic :( NSDictionary *) dictionary {NSInteger num1; id num1Obj = [dictionary objectForKey: @ "num1"]; if (num1Obj) {if ([num1Obj isKindOfClass: [NSNumber class]) {num1 = [num1Obj integerValue];} else if ([num1Obj isKindOfClass: [NSString class]) {num1 = [num1Obj integerValue];} NSDictionary * dic = [dictionary objectForKey: @ "dic"]; if (dic & [dic isKindOfClass: [NSDictionary class]) {// continue processing }//... Other NSString * keys; // or, if you encounter a key with passed values, you need to determine whether the key exists (otherwise it will crash) if (key) {NSString * string = [dic objectForKey: key] ;}}
After using my fault tolerance library
-(Void) parseDic :( NSDictionary *) dictionary {NSInteger num1 = [dictionary integerForKeySafe: @ "num1"]; NSDictionary * dic = [dictionary dictionaryForKeySafe: @ "dic"]; //... Other NSString * keys; // or, if you encounter a key with passed values, you need to determine whether the key exists NSString * string = [dic objectForKeySafe: key];}
Since then, it is easy to parse and write, and Mom no longer has to worry about your failure tolerance!
I have handled the following situations, including:
1. NSString numeric conversion and string Truncation
2. NSNumber numeric Conversion
3. Various NSDictionary values and null key Processing
4. handling various cross-border situations of NSArray
5 ....
When an error occurs, for example, if a dic is required for parsing but the return type is string, the nil will be obtained using my fault tolerance library. Since any message of nil can be safely executed, therefore, no crash occurs.
In fact, similar libraries in the iOS development industry also exist, such as DurexKit and VDM. If you are interested, you can check it out.
In addition, I did not use runtime to replace the system method, and left it to the developer to choose whether to use the fault tolerance method. After all, some developers can save some performance by making a few judgments.
You are welcome to leave a message.