gpt4 book ai didi

ios - 自动设置 NSString 属性的默认值

转载 作者:行者123 更新时间:2023-11-29 12:21:02 24 4
gpt4 key购买 nike

我的代码中有许多 bean/数据类,我使用它们将它们转换为 JSON 以用于网络通信目的。问题是,如果我的类中有一个 NSString 属性,我想将其默认值设置为空字符串 @"" 而不是 nil。我有一个选择是:Setting Default Values For NSString Properties但我必须编写代码来设置属性值,我不想这样做。

我尝试使用 Objc 运行时获取所有属性并做了如下操作:

    unsigned int numberOfProperties = 0;
objc_property_t *propertyArray = class_copyPropertyList([self class], &numberOfProperties);

for (NSUInteger i = 0; i < numberOfProperties; i++)
{
objc_property_t property = propertyArray[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
const char * propAttr = property_getAttributes(property);
NSString *propString = [NSString stringWithUTF8String:propAttr];
NSArray *attrArray = [propString componentsSeparatedByString:@"\""];
if (attrArray.count > 0) {
NSString *propType = [attrArray objectAtIndex:1];
if ([propType containsString:@"NSString"]) {
[self setValue:@"" forKey:name];
}
}

}
free(propertyArray);

这对我来说就像一个魅力。唯一的问题是我继承了类,这段代码只设置了子类的值,它没有设置基类中的属性值。我正在使用 xcode 6.3.1 和 iOS 8.x。任何帮助深表感谢。谢谢

最佳答案

您可以在 bean/数据基类中定义一个递归方法 setDefaultPropValuesForClass:,例如Bean,并从基类的 init 方法中调用它。请参阅下面的实现:

@interface Bean : NSObject
// Add your props
// ...
// .....
@end

@implementation Bean

- (instancetype)init {
self = [super init];
if (self) {
[self setDefaultPropValues];
// TODO: All other initializations
}
return self;
}

- (void)setDefaultPropValues {
[self setDefaultPropValuesForClass:self.class];
}

- (void)setDefaultPropValuesForClass:(Class)refClass {
if (![refClass isSubclassOfClass:[Bean class]]) {
return;
}
// First set default property values in super classes
Class baseClass = class_getSuperclass(refClass);
[self setDefaultPropValuesForClass:baseClass];
//
unsigned int numberOfProperties = 0;
objc_property_t *propertyArray = class_copyPropertyList(refClass, &numberOfProperties);
for (NSUInteger i = 0; i < numberOfProperties; i++)
{
objc_property_t property = propertyArray[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
const char * propAttr = property_getAttributes(property);
NSString *propString = [NSString stringWithUTF8String:propAttr];
NSArray *allAttrs = [propString componentsSeparatedByString:@","];
// Check if property is readonly
if (NSNotFound == [allAttrs indexOfObject:@"R"]) {
// Find Property type token
NSArray * attrArray = [propString componentsSeparatedByString:@"\""];
if (attrArray.count > 1) {
Class propType = NSClassFromString([attrArray objectAtIndex:1]);
if ([propType isSubclassOfClass:[NSString class]]) {
[self setValue:@"" forKey:name];
}
}
}
}
free(propertyArray);
}

@end

关于ios - 自动设置 NSString 属性的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30634415/

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