1. 程式人生 > >iOS runtime——函式/使用方法/使用場景/示例

iOS runtime——函式/使用方法/使用場景/示例

JSONModel方法實現順序
//  物件屬性的獲取則主要在最後一個inspectProperties方法
-(void)__inspectProperties
{
    //JMLog(@"Inspect class: %@", [self class]);

    NSMutableDictionary* propertyIndex = [NSMutableDictionary dictionary];

    //temp variables for the loops
    Class class = [self class];
    NSScanner* scanner = nil;
    NSString* propertyType = nil;

    // inspect inherited properties up to the JSONModel class
    while (class != [JSONModel class]) 
    {
        //JMLog(@"inspecting: %@", NSStringFromClass(class));

        unsigned int propertyCount;
        objc_property_t *properties = class_copyPropertyList(class, &propertyCount);

        // loop over the class properties
        for (unsigned int i = 0; i < propertyCount; i++) 
        {
            JSONModelClassProperty* p = [[JSONModelClassProperty alloc] init];

            // get property name
            objc_property_t property = properties[i];
            const char *propertyName = property_getName(property);
            p.name = [NSString stringWithUTF8String:propertyName];

            // JMLog(@"property: %@", p.name);

            // get property attributes
            const char *attrs = property_getAttributes(property);
            NSString* propertyAttributes = [NSString stringWithUTF8String:attrs];

            if ([propertyAttributes hasPrefix:@"Tc,"]) 
           {
                //mask BOOLs as structs so they can have custom convertors
                p.structName = @"BOOL";
            }

            scanner = [NSScanner scannerWithString: propertyAttributes];

            //JMLog(@"attr: %@", [NSString stringWithCString:attrs encoding:NSUTF8StringEncoding]);
            [scanner scanUpToString:@"T" intoString: nil];
            [scanner scanString:@"T" intoString:nil];

···

//finally store the property index in the static property index
objc_setAssociatedObject(self.class,
                         &kClassPropertiesKey,
                         [propertyIndex copy],
                         OBJC_ASSOCIATION_RETAIN // This is atomic
                         );