美文网首页
【OC梳理】description

【OC梳理】description

作者: 忠橙_g | 来源:发表于2018-08-30 17:34 被阅读20次

iOS中,使用NSLog输出NSObject对象时常使用%@修饰,其输出结果一般类似:

 <Object: 0x1234567890>

这样的输出并没什么鸟用,如果想让输出的结果更加清晰,可以在子类中重写- (NSString *)description;方法,返回想要输出的信息,例如:

// ...
@property (nonatomic, copy, readonly) NSString * name;
@property (nonatomic, copy, readonly) NSString * address;
// ...
- (NSString *)description{
    return [NSString stringWithFormat:@"<%@ : %p, \"%@ %@\">", [self class], self, _name, _address];
}

使用NSLog输出该对象:

... <Object: 0x123456789, "_name _address">

或者我们可以将属性放到NSDictionary中,让输出更加清晰:

// ...
- (NSString *)description{
    return  [NSString stringWithFormat:@“%@-> %p: \n%@”, [self class], self, @{@"name":_name,
                    @"address":_address}];
}

输出结果为:

Object:-> 0x123456789:
{
    name = _name;
    address = _address;
}

如果我们更懒一点,使用runtime遍历属性进行输出:

// ...
#import <objc/runtime.h>
// ...
- (NSString *)description{
    unsigned int count ,i;
    objc_property_t *propertyArray = class_copyPropertyList([self class], &count);
    NSMutableDictionary *mutDic = [NSMutableDictionary dictionary];
    for (i = 0; i < count; i++) {
        objc_property_t property = propertyArray[i];
        NSString *proKey = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        id proValue = [self valueForKey:proKey];
        
        if (proValue) {
            [mutDic setObject:proValue forKey:proKey];
        } else {
            [mutDic setObject:@"" forKey:proKey];
        }
    }
    free(propertyArray);
    return  [NSString stringWithFormat:@"%@: %p, \n%@", [self class], self, mutDic];
}

同时,我们在debugDescription中实现相同的代码,以便于调试时使用po命令输出相同的结果。

相关文章

  • 【OC梳理】description

    iOS中,使用NSLog输出NSObject对象时常使用%@修饰,其输出结果一般类似: 这样的输出并没什么鸟用,如...

  • oc Description

    标签:ios开发入门 //自定义类用NSLog是输出不了的,输出的是它的地址,而在后面实现了description...

  • description方法 - OC

    使用:当我们以%@的格式打印对象的时候,就会调用当前对象的description方法

  • mysql update正则替换sql语句

    update`oc_product_description`setdescription=replace(desc...

  • Objective-C 中关于description的探讨

    在OC中,Description方法包括类方法和对象方法,而我们通常所重写的description方法一般是重写对...

  • OC与Swift中的 description

    Swift 中重写父类description方法,输出模型中的内容 OC中 在自定义的类中,将其中的属性在desc...

  • 【OC梳理】runtime

    什么是runtime runtime是属于OC的底层,可以进行一些非常底层的操作(用OC是无法现实的, 不好实现)...

  • 【OC梳理】NSUserDefaults

    概述 NSUserDefaults可以用来保存应用程序设置和属性、用户保存的数据。 用户再次打开程序或开机后这些数...

  • 【OC梳理】NSPredicate

    NSPredicate NSPredicate(谓词),可以根据定义的模糊查询条件,对内存对象进行过滤搜索。 基本...

  • 【OC梳理】CoreData

    CoreData 是 Cocoa 平台上用来管理模型层数据和数据持久化的一个框架。它的概况可以参考认识CoreDa...

网友评论

      本文标题:【OC梳理】description

      本文链接:https://www.haomeiwen.com/subject/jzrdwftx.html