I have this initializer for an object:
-(id)init
{
self = [super init];
if (self) {
if([[NSUserDefaults standardUserDefaults] objectForKey:kTermsAccepted] != nil){
_termsAccepted = [[NSUserDefaults standardUserDefaults] boolForKey:kTermsAccepted];
}
if([[NSUserDefaults standardUserDefaults] objectForKey:kInitialSetupCompleted] != nil){
_initialSetupCompleted = [[NSUserDefaults standardUserDefaults] boolForKey:kInitialSetupCompleted];
}
if([[NSUserDefaults standardUserDefaults] objectForKey:kDashboardMessage] != nil){
_dashboardMessage = [[NSUserDefaults standardUserDefaults] objectForKey:kDashboardMessage];
} else{
_dashboardMessage = [[NSBundle mainBundle] localizedStringForKey:kDMDefaultDashboardMessage value:kDMDefaultDashboardMessage table:nil];
}
//50 other if statements
}
return self;
}
What would be a better way to do this so I don't get these warnings while doing an OCLint analysis?
Thanks!
All instance variables are initialised to 0; that means that
BOOLs are initialised toNO. Therefore the effect of:... is: if there is a stored value then set
_termsAcceptedto it. Otherwise_termsAcceptedwill beNO.boolForKey:has a documented return value of:So compare and contrast with just:
... in that case the net result will be: if there is a stored value then set
_termsAcceptedto it. Otherwise_termsAcceptedwill beNO.So to reduce cyclomatic complexity, drop the
ifstatements. They add nothing.EDIT: it's been correctly pointed out that I've missed the fact that
BOOLs are not exclusively in use.Use
-[NSUserDefaults registerDefaults:]to establish your fallback values. Those are kept in memory once set but not written to the store. Then the user defaults themselves will handle the "if no value stored, use this value" case for all types of object.