I always wonder, should we use NSClassFromString before using any built in class in our code to make is generic. Or is there any standard practice to use this. Same thing for property. Should we use valueForKey and setValue calls separately to access any property. Is it a standard practice?
For example look at the below code
// Screen scaling
if ([self respondsToSelector:@selector(setContentsScale:)])
{
Class screenClass = NSClassFromString(@"UIScreen");
if ( screenClass != Nil)
{
id scale = [[screenClass mainScreen] valueForKey:@"scale"];
[(id)self setValue:scale forKey:@"contentsScale"];
}
}
Here everything is checked before use. Is it required to do this and what about performance?
No, this is only for classes which you don’t know whether they do exist in your environment or which are dynamically loaded at runtime (something iOS doesn’t allow but is available on Mac OS X, so you don’t need to care about that).
You need to do this e.g. if you want to support 3.0 devices, but use 4.x classes if they are available, like GameKit classes. Since UIScreen is available since 2.0 you don’t need to use NSClassFromString here. But you would need to check for the presence of
scalesince it was added in 4.0, andvalueForKey:@"scale"will raise aNSUndefinedKeyExceptionon pre-4.0 devices.Instead of key-value coding, you could also do this: