思路:既然我们需要改变NSArry和NSDictionary的系统类方法,所以我们可以利用运行时runtime来进行方法交换、另一种方法就是通过添加分类来重写类方法的实现。注意:这里不是添加类扩展。
为NSArry和NSDictionary添加分类
分类中的实现:
方式一:
删除.h文件(因为在项目里打印字典或数组时,使用的是系统的方法并不需要导入分类的头文件),.m文件下的实现,
#import <Foundation/Foundation.h>
@implementation NSDictionary (Log)
//重写系统的方法控制输出
-(NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
{
NSMutableString *string = [NSMutableString string];
//{}
[string appendString:@"{"];
//拼接key--value
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
[string appendFormat:@"%@:",key];
[string appendFormat:@"%@,",obj];
}];
[string appendString:@"}"];
//删除逗号
//从后往前搜索 得到的是搜索到的第一个符号的位置
NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
if (range.location != NSNotFound) {
[string deleteCharactersInRange:range];
}
return string;
}
@end
@implementation NSArray (Log)
//重写系统的方法控制输出
-(NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
{
// return @"你大爷是你大姐";
NSMutableString *string = [NSMutableString string];
//{}
[string appendString:@"["];
//拼接obj
[self enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[string appendFormat:@"%@,\n",obj];
}];
[string appendString:@"]"];
//删除逗号
//从后往前搜索 得到的是搜索到的第一个符号的位置
NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
if (range.location != NSNotFound) {
[string deleteCharactersInRange:range];
}
return string;
}
@end
方式二:
.h文件
#import <Foundation/Foundation.h>
@interface NSArray (desc)
@end
@interface NSDictionary (desc)
@end
.m文件
#import "NSArray+desc.h"
@implementation NSArray (desc)
- (NSString *)descriptionWithLocale:(id)locale
{
NSMutableString *strM = [NSMutableString stringWithString:@"(\n"];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[strM appendFormat:@"\t%@,\n", obj];
}];
[strM appendString:@")"];
return strM;
}
@end
@implementation NSDictionary (desc)
- (NSString *)descriptionWithLocale:(id)locale
{
NSMutableString *strM = [NSMutableString stringWithString:@"{\n"];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[strM appendFormat:@"\t%@ = %@;\n", key, obj];
}];
[strM appendString:@"}\n"];
return strM;
}
@end