Reputation: 3370
I have a method in my class that receives a @selector
and an object (id
), and that particular method returns an id
(which is the returning value after I performed the @selector
on the object I received).
So, here's what I have for the return
of my method (this is only one line, I have a line for each primitive type: int, short, long, etc...):
return [NSNumber numberWithChar:[obj performSelector:sel]];
And Xcode gives me this warning, which is a very good point:
Incompatible pointer to integer conversion sending 'id' to parameter of type 'char'
But, the thing is, before I execute the return
above with the according NSNumber
's -numberWith...
, I make sure that the type of the value returned by [obj performSelector:sel]
is the correct one, so I want to hide the Xcode's warning because it doesn't help me with anything.
I've tried [NSNumber numberWithChar:[[obj performSelector:sel] charValue]]
to work around the warning (this made the warning go away) but my program crashes now, with that new charValue
.
Any ideas on how to hide the error (no matter of what type is) or how to fix it?
Thanks!
Upvotes: 1
Views: 692
Reputation: 7534
you seriously don't want to ignore these warnings. In the event that they are actually invalid you should be using a C cast to 'hide' the warning.
If this is one of those cases then do this:
return [NSNumber numberWithChar:(char)[obj performSelector:sel]];
I don't know that performSelector:
will return a non object, I'm pretty sure the docs say to use NSInvocation
for such cases, but I cannot find it ATM, will update if I do.
Edit: The docs indeed say to use NSInvocation
for methods that don't return an objective-c object.
Upvotes: 1
Reputation: 237110
Well, the general fix is to use an explicit message send instead of performSelector:
, because performSelector:
expects the method to return an object and won't always work correctly when the method returns something else. So you want return [NSNumber numberWithChar:[obj whateverSelContains]]
.
However, you can probably use Key-Value Coding as a substitute for performSelector:
here. It's hard to say without seeing your real code, but assuming this is a no-argument method that returns a char, that approach should work. In that case, you'll want a string instead of a SEL. Then you can do [[obj valueForKey:whateverWasInSel] charValue]
and that will work.
Upvotes: 3
Reputation: 53010
The documentation for performSelector:
contains the answer:
For methods that return anything other than an object, use
NSInvocation
.
Values of different types may be returned differently (using different registers, on the stack, etc.). What you are trying to do is take a selector defined to return an id
and treat the result as though it is some other (primitive) type. It may work, but it is not guaranteed or required to work.
So don't hide try to hide the error, fix your code!
Upvotes: 4