in Objective-c I have this function prototype: -(NSString*)formatSQL:(NSString*) sql, ... I may pass to this function any type of parameters: NSString, NSNumber, integer, float How can I determine in the function if a parameter is an object (NSString..) or a primitive (integer...)? thanks BrochPirate
If you're going to have a parameter that accepts multiple types, you can only safely do it by using Obj-C objects, which means using id
as the type. You can't safely inter-mingle id
with float
, integer
etc.
If you wrapped up all float
s and int
s in NSNumber
s, you could have a method like so:
- (NSString *)formatSQL:(id)obj
{
if ([obj isKindOfClass:[NSString class]]) {
// Format as a string
}
else if ([obj isKindOfClass:[NSNumber class]]) {
// Further processing will be required to differentiate between ints and floats
}
}
There are a few caveats to using isKindOfClass:
, but this should serve as a good starting point.
Tried this. The thing is, if the parameter (say 'obj'), is a primitive (interger, float), the command: [obj isKindOfClass:... kills the app with "bad access" error. This error is not trapable by @try/@catch - otherwise this would have been a way to identify the type. thanks though, Broch
I understand that an NSNumber wrapper would circumvent the initial propblem, however I am trying to minimize the impact on other code pieces therefore woluld appriciate a way to distinguish between 'object' an 'primitive'.
It might help if I had a way to assert whether an object (actually a pointer) points to a valid address within my address space...
Thanks Broch