我有一个具有一些属性的单例对象,我想将所有这些值设置为nil或" NO"基于属性的类型。一种方法是编写一个重置方法,我将所有这些属性设置为nil,就像下面一样。
这甚至可能包含要清除的实例变量。
-(void)reset
{
//Properties
self.lastLoggedInUser = nil;
self.localMasterDownload = NO;
self.isFirstLaunchDone = NO;
self.lastArchvingDate = nil;
self.archivingDueDate = nil;
self.dbEncryptionKey = nil;
self.checkInDone = NO;
//Instance variables
_isPostionModuleExtandedMode = NO;
_isPassengerModuleExtandedMode = NO;
}
但我正在寻找一种更通用,更有效的方法。
感谢任何帮助。
感谢。
答案 0 :(得分:1)
这将为您提供类属性,从那里您只需要将键字符串转换为可以将属性转换为nil的内容。我认为这是可能的。
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
unsigned count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++) {
NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
if([self valueForKey:key]!=nil){
[dict setObject:[self valueForKey:key] forKey:key];
}else{
[dict setObject:@NO forKey:key];
}
}
free(properties);
return [NSDictionary dictionaryWithDictionary:dict];
答案 1 :(得分:0)
- (void) resetProperties {
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];
const char *propName = property_getName(property);
if(propName) {
NSString *propertyName = [NSString stringWithCString:propName encoding:[NSString defaultCStringEncoding]];
id value = [self valueForKey:propertyName];
NSLog(@"[berore]XXXresetProperties => [%@] %@=%@", [propertyName class],propertyName, value);
/* You can add some other checks */
if ([value isKindOfClass:[NSNumber class]]) {
[self setValue:[NSNumber numberWithInteger:0] forKeyPath:propertyName];
}
if ([value isKindOfClass:[NSString class]]) {
[self setValue:nil forKeyPath:propertyName];
}
if ([value isKindOfClass:[NSDictionary class]]) {
[self setValue:nil forKeyPath:propertyName];
}
id valueRes = [self valueForKey:propertyName];
NSLog(@"[after]XXXresetProperties => [%@] %@=%@\n---\n", [propertyName class],propertyName, valueRes);
}
}
free(properties);
}
你可以在那里得到它: https://github.com/energy6x6/iOS-clear-all-property-in-class