Runtime 简单了解

作者: 漂泊海上的大土豆 | 来源:发表于2017-05-10 10:59 被阅读72次

copy 类中的 property

/** 
 * Describes the properties declared by a class.
 * 
 * @param cls The class you want to inspect.
 * @param outCount On return, contains the length of the returned array. 
 *  If \e outCount is \c NULL, the length is not returned.        
 * 
 * @return An array of pointers of type \c objc_property_t describing the properties 
 *  declared by the class. Any properties declared by superclasses are not included. 
 *  The array contains \c *outCount pointers followed by a \c NULL terminator. You must free the array with \c free().
 * 
 *  If \e cls declares no properties, or \e cls is \c Nil, returns \c NULL and \c *outCount is \c 0.
 */
OBJC_EXPORT objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);

返回 property 的 name

/** 
 * Returns the name of a property.
 * 
 * @param property The property you want to inquire about.
 * 
 * @return A C string containing the property's name.
 */
OBJC_EXPORT const char *property_getName(objc_property_t property) 
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);

实战 通过类名得到类中的属性名

// 通过类名得到类中的属性名
+ (NSArray *)getPropertyNameArrayWithClassName:(NSString *)className {
    NSMutableArray *array = [NSMutableArray array];
    unsigned int count;
    objc_property_t *props = class_copyPropertyList(NSClassFromString(className), &count);
    
    for (int i = 0; i < count; i ++) {
        objc_property_t property = props[i];
        const char *name = property_getName(property);
        
        NSString *propertyName = [NSString stringWithUTF8String:name];
        [array addObject:propertyName];
    }
    
    free(props);
    
    return array;
}

相关文章

网友评论

    本文标题:Runtime 简单了解

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