? Possible ?: Making a method that accepts either an object or primative?

boyfarrell

Registered
Hi folks,

Is it possible to make a method that only has one argument that can be either a object or a primative?

For example, can I compress these two into one method and then use a if statement in the implementation to find out whether it was passed a double datatype, say, or a object:

Code:
-(CustomClass*) multiply: (CustomClass*) input;
-(CustomClass*) multiply: (double) input;
Shrinking this to,
Code:
-(CustomClass*) multiply: (superSpecialId) input;
 
you can use : (void *) input, but I think you would need to make sure that you are passing a pointer to the double, rather than the double value. you would also need to figure out a way to figure out what is being passed. Off the top of my head, you could maybe check:
Code:
if (sizeof(*input) == sizeof(double))
 
Yeah I thought about asking the size of it two.

I can get round this simply by making another method! But that doesn't appeal to my sense of fun!

The method doesn't have to be that general it will ONLY ever need to accept a double of a CustomClass* (which I have made).
 
I guess the only way to really do this is rather than input a double input a NSNumber containing a double and use id as the datatype for the input. Inside the methodyou can as us
Code:
if(inputObject == NSNumber) etc ....

Infact how do I ask an object what class it is from in this way?
 
You could use NSObject's isMemberOfClass: method, e.g.:
if ([inputObject isMemberOfClass:[NSNumber class]]) doStuffHere;

There are ways to make methods that can take an arbitrary number of arguments, isn't there? In such cases, do you ever need to specify the argument types in the declaration? I don't know since I've never done this, but it might be worth looking into.
 
Well this works. Not quite as simple as I wanted it, I have to sent it a NSNumber rather than a primative but hey how slick can you be....

Code:
-(CustomClass*) add: (id) inputObject
{	
	if ([inputObject isKindOfClass:[CustomClass class]])
	{
          //Do stuff with inputObject when it is a CustomClass
	}
	else if ([inputObject isKindOfClass:[NSNumber class]])
	{	
         //Do stuff with inputObject when it as a NSNumber
	}
	else
	{
	    printf("\n\nError: Enter either a CustomClass or a NSNumber in -add:\n\n");
	    exit(1);
	}
}
 
Back
Top