ios - Can I trust objectForKey right after setObject in NSCache? -
considering sample code (cache instance of nscache):
- (id)objfromcache { if ([cache objectforkey:@"myobject"] == nil) [cache setobject:[self generateobject] forkey:@"myobject"]; return [cache objectforkey:@"myobject"]; }
should trust code? mean, objectforkey:@"myobject"
ever return nil right after setobject:forkey:@"myobject"
? if so, whould change if
while
?
what's best way handle situation? thanks!
at least in multi-threaded environment cannot assume nscache
returns object inserted.
also if first call [cache objectforkey:@"myobject"]
not return nil
, second 1 in return statement return nil
.
so play safe , write method as
- (id)objfromcache { id value = [cache objectforkey:@"myobject"]; if (value == nil) { value = [self generateobject]; [cache setobject:value forkey:@"myobject"]; } return value; }
Comments
Post a Comment