测试已测试 | ✓ |
语言语言 | Obj-CObjective C |
许可证 | MIT |
发布时间上次发布 | 2016年7月 |
由Andrea Cipriani维护。
- (NSString*)description
{
😱 😱 😱 ⌛️⌛️⌛️
}
写描述方法很无聊,每次修改类都要更新,更无聊的是要保持其更新。但是好的描述可以改善你的调试质量...还可以节省你的时间!
AGCDescription
为你做脏活了!
AGCDescription
是NSObject
的一个分类,它使用Objective-c运行时特性来自动构建任何类描述字符串。如果你更改了类,描述将自动更新。
给定一个代表用户的简单类
@interface AGCUser : NSObject
- (instancetype)initWithUserId:(NSNumber*)userId username:(NSString*)username password:(NSString*)password userImage:(UIImage*)userImage;
@property (nonatomic, strong) NSNumber* userId;
@property (nonatomic, copy) NSString* username;
@property (nonatomic, copy) NSString* password;
@property (nonatomic, strong) UIImage* userImage;
转到实现文件,导入分类
#import "NSObject+AGCDescription.h"
并将AGCDescription
代理到返回描述字符串
- (NSString*)description
{
return [self agc_description];
}
- (NSString*)debugDescription
{
return [self agc_debugDescription];
}
这就完成了。很简单,不是吗?现在让我们打印用户的描述来查看结果
AGCUser* agcUser = [[AGCUser alloc] initWithUserId:@(123) username:@"Mick Jagger" password:@"angie123" userImage:[UIImage imageNamed:@"mick.png"]];
NSLog(@"%@",agcUser);
将输出以下内容
<AGCUser:
{
userId = 123;
username = Mick Jagger;
password = angie123;
userImage = <UIImage: 0x7faa7a5fb170>, {140, 154};
}>
而且不仅如此!假设几天后你决定用户应该还有电子邮件地址属性。你把它添加到你的类中
@property (nonatomic, copy) NSString* emailAddress;
//...
[agcUser setEmailAddress:@"[email protected]]
并且你不需要更改你的代码!描述将自动更新 - 如果删除或重命名属性,描述也会自动更新。
<AGCUser:
{
userId = 123;
username = Mick Jagger;
password = angie123;
userImage = <UIImage: 0x7faa7a5fb170>, {140, 154};
emailAddress = [email protected]
}>
如果你不想记录用户的密码?或者你只想忽略那些对描述没有影响的属性(例如,用户图像),请使用agc_descriptionIgnoringPropertiesWithNames
方法
- (NSString*)description
{
return [self agc_descriptionIgnoringPropertiesWithNames:@[@"password",@"userImage"]];
}
这样你就可以保护你的秘密了
<AGCUser:
{
userId = 123;
username = Mick Jagger;
emailAddress = [email protected]
}>
让我们看看AGCDescription
是如何构建描述字符串的
格式是
<$ClassName:
{
$firstPropertyName = $firstPropertyValue;
...
$lastPropertyName = $lastPropertyValue;
}>
hash, description, debugDescription
有时属性值过长,无法放入描述中。在这种情况下,使用所谓的“简短描述”,其基本格式如下
<$ClassName: $objectAddress>
以下是评估属性值的规则
要运行示例项目,首先从示例目录克隆仓库,然后运行 pod install
iOS 8+ 和 ARC
AGCDescription 可以通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中
pod "AGCDescription"
Andrea Cipriani, [email protected] - Twitter @AndreaCipriani
AGCDescription 在 MIT 许可下可用。有关更多信息,请参阅 LICENSE 文件。