gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:49:29 24 4
gpt4 key购买 nike

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

@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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com