cocoa 检测对象是否存在某一个成员变量属性

//检测对象是否存在该属性 不带下划线的成员变量名

  • (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName{
    unsigned int count;
    //获取对象里的属性列表
    objc_property_t *properties = class_copyPropertyList([instance class], &count);
    NSMutableArray *nameArray = [[NSMutableArray alloc] initWithCapacity:count];
    for (int i = 0; i < count; i++) {
    objc_property_t property = properties[i];
    //属性名转为字符串
    NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
    //判断属性是否存在
    if ([propertyName isEqualToString:verifyPropertyName]) {
    free(properties);
    return YES;
    }
    [nameArray addObject:propertyName];
    }
    free(properties);
    return NO;
    }

//获取类的成员变量名 带下划线的成员变量名

  • (NSArray *)getVariableNamesByObject:(id)object verifyPropertyName:(NSString *)verifyPropertyName{
    unsigned int numIvars = 0;
    //获取类的所有成员变量
    Ivar * ivars = class_copyIvarList([object class], &numIvars);
    //定义一个数组来接收获取的属性名
    NSMutableArray *nameArray = [[NSMutableArray alloc] initWithCapacity:numIvars];
    for(int i = 0; i < numIvars; i++) {
    //得到单个的成员变量
    Ivar thisIvar = ivars[i];
    //得到这个成员变量的类型
    const char *type = ivar_getTypeEncoding(thisIvar);
    NSString *stringType = [NSString stringWithCString:type encoding:NSUTF8StringEncoding];
    //此处判断非object-c类型时跳过
    if (![stringType hasPrefix:@"@"]) {
    continue;
    }
    //得到成员变量名
    NSString *variableName = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
    [nameArray addObject:variableName];
    //这个函数可以得到成员变量的值
    if ([variableName hasSuffix:verifyPropertyName]) {
    id type1 = object_getIvar(object, thisIvar);
    NSLog(@"%@",[(NSTextField *)type1 stringValue]);
    }
    }
    free(ivars);
    return nameArray;
    }

你可能感兴趣的:(cocoa 检测对象是否存在某一个成员变量属性)