ios - 如何在 Objective-C iOS 中迭代和设置类的属性

标签 ios objective-c properties

我有一个模型类对象,它具有以下属性

@property (nonatomic, strong) NSString *place;
@property (nonatomic, strong) NSString *date;

我从 Controller 类对象设置这些属性。

我想对我的模型类对象属性执行空检查。所以我想写一个如下的for循环。
for (property in modelObject)
{   
 if (object  == [NSNull null])//object is a property of modelobject
 {  
   //the next two lines wont be true but need to check that 
   if([property isKindOfClass:[NSString Class]]) property = @"no place";
   if([property isKindOfClass:[NSDate Class]]) property = @"No date;
 }
}

我的问题是,

如果模型类对象属性设置为 null 我如何检查该属性是否为 null 以及该属性的声明类型?

直接检查这两个属性而不是循环遍历属性是没有用的,因为在实际场景中,模型类有很多不同类型的属性。

提前致谢。

最佳答案

在模型类中添加方法

- (void)nullCheck {
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)];
        id propertyValue = [self valueForKey:(NSString *)propertyName]; //check propertyValue here
        //set property value here 
        [self setValue:@"some value" forKey:(NSString *)propertyName];
        const char * type = property_getAttributes(property);
        NSString *attr = [NSString stringWithCString:type encoding:NSUTF8StringEncoding];

        NSString * typeString = [NSString stringWithUTF8String:type];
        NSArray * attributes = [typeString componentsSeparatedByString:@","];
        NSString * typeAttribute = [attributes objectAtIndex:0];
        NSString * propertyType = [typeAttribute substringFromIndex:1];
    }
    free(properties);
}

关于ios - 如何在 Objective-C iOS 中迭代和设置类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32332674/

相关文章:

ios - 升级到 xcode 7 后无法在设备上运行应用程序

ios - 在 iOS 上使用 Core Image 的内存高效方式?

javascript - 从 javascript 属性和值中删除\r

delphi - 有没有办法在 Delphi 6 中自动分配动态创建的组件的事件处理程序?

angular - Angular 形|当我使用2 ngIf时,如何读取子组件的属性?

ios - 在核心数据中保存一个整数

iphone - 动态表格 View 中的静态表格单元格?

ios - 将 scrollOffset 保存到 didEndDisplayingCell 中的 UITableView 数据源未正确出列

ios - UIButton 的动画背景颜色从白色变为红色

iOS通过按钮调用按钮 Action