PEAKを生きる

科学の力で、能力を最大化するブログ

【iOS】モデルクラス用にdescriptionを拡張する

背景

よくデータは、プロパティだけのクラスを作りモデルクラスとして扱うことが多いのですが、NSLogで出力すると<モデル名: 0xb1ddb00>というかなしいログが吐き出されます。

その悲しさをバネに、プロパティの中身を表示するメソッドを作ってみました。結構便利。

コード

NSObjectdescriptionというメソッドがあり、こいつをオーバライドしちゃえば、NSLog(@"%@",modelInstance);とかとすれば、descriptionを呼び出し、それを出力してくれます!

便利!ということでコード。プリミティブ型が非対応です。

- (NSString *)description{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    NSMutableString *description = [NSMutableString stringWithFormat:@"%@ : %@ = \n(",[super description], NSStringFromClass([self class])];
    for(i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        const char *propName = property_getName(property);
        const char *propType = property_getAttributes(property);
        NSString *propertyName = @(propName);
        NSString *propertyType = @(propType);
        SEL selector = NSSelectorFromString(propertyName);
        NSString *propertyString = @"";
        if ([self respondsToSelector:selector] && [propertyType hasPrefix:@"T@"]) {
            propertyString  = [NSString stringWithFormat:@"%@: %@ \n", propertyName, [self performSelector:selector]];
        }else{
            propertyString = [NSString stringWithFormat:@"%@: プリミティブは非対応 %@\n",propertyName, propertyType];
        }
        [description appendString:propertyString];
    }
    [description appendString:@")"];
    free(properties);
    return description;
}

いや、そんなことせんでも。。。みたいなのがあれば教えて下さい。

参考

(旧) Cocoaの日々: @property の一覧を取得する
(旧) Cocoaの日々: @property の一覧を取得する