在 Objective C 中检查 isKindOfClass 是否多余?
Is it redundant to check isKindOfClass in Objective C?
即使对于 Objective C 中的非 id 变量,检查 isKindOfClass 是否多余?
队友编写了 Swift 代码。我正在复习。我真的需要检查条件中的 isKindOfClass
还是多余的?
-(void) checkCalorie:(NSMutableDictionary *) update {
NSString *foodInfoId = [update objectForKey:FOOD_INFO_ID];
double calorie = [[update objectForKey:CALORIE] doubleValue];
if ([foodInfoId isKindOfClass:[NSString class]] && calorie < 0)
{
calorie = 0.0;
// some logic
}
}
我认为您应该使用为 Objective-C 实现的 dynamic_cast
重构此代码。你可以检查this question for inspiration. For instance, use objc_dynamic_cast
from this answer,然后你将有以下代码:
-(void)checkCalorie:(NSMutableDictionary *)update {
NSString *foodInfoId = objc_dynamic_cast([update objectForKey:FOOD_INFO_ID], NSString);
double calorie = [[update objectForKey:CALORIE] doubleValue];
if (foodInfoId != nil && calorie < 0) {
calorie = 0.0;
// some logic
}
}
即使对于 Objective C 中的非 id 变量,检查 isKindOfClass 是否多余?
队友编写了 Swift 代码。我正在复习。我真的需要检查条件中的 isKindOfClass
还是多余的?
-(void) checkCalorie:(NSMutableDictionary *) update {
NSString *foodInfoId = [update objectForKey:FOOD_INFO_ID];
double calorie = [[update objectForKey:CALORIE] doubleValue];
if ([foodInfoId isKindOfClass:[NSString class]] && calorie < 0)
{
calorie = 0.0;
// some logic
}
}
我认为您应该使用为 Objective-C 实现的 dynamic_cast
重构此代码。你可以检查this question for inspiration. For instance, use objc_dynamic_cast
from this answer,然后你将有以下代码:
-(void)checkCalorie:(NSMutableDictionary *)update {
NSString *foodInfoId = objc_dynamic_cast([update objectForKey:FOOD_INFO_ID], NSString);
double calorie = [[update objectForKey:CALORIE] doubleValue];
if (foodInfoId != nil && calorie < 0) {
calorie = 0.0;
// some logic
}
}