views:

20

answers:

2

I've got a function called updateTheValue() that I have called using [self updateTheValue] for a while now. Two things happened recently; I added the method calling in the viewDidLoad() method and it spit out a warning saying my class may not respond to this. Second, I want to pass objects to updateTheValue() like strings, but mostly ints, so I declared an NSObject to pass into the method. Can an int fit into an NSObject slot, or what should I use instead?

I would have posted these seperately but they seem to be related since after updating updateTheValue() to accept an NSObject every reference to this function turns out the error that my class "May not respond to -updateTheValue"

A: 

First problem:

updateTheValue() must be declared before you try to call it.

You can either move the definition of function before the calls to it, or add a prototype at the top - eg, add:

  • (void) updateTheValue;

near the top.

Second problem:

Use an NSNumber, eg [NSNumber numberWithInt:45];

JosephH
+3  A: 

You could make your method like this:

-(void)updateTheValue:(NSObject *)anObject
// or use -(void)updateTheValue:(id)anObject
{
   if ([anObject isKindOfClass:[NSString class]]) {
      // Do your string handling here
   }
   else if ([anObject isKindOfClass:[NSNumber class]]) {
      // Do your number handling here
   }
}

Use it like this:

[self updateTheValue:[NSNumber numberWithInt:42]];

I'd suggest doing two different methods though, i.e. updateTheValueWithInt: and updateTheValueWithString: making it easier to read and understand.

Make sure you make the method signature visible before using them, so that the compiler knows what this does.

If you use separate methods you can use int directly without wrapping them into NSNumber objects.

Eiko
I agree. In Objective-C it's not normal to create methods with arguments of type `id` to allow for disparate classes. It is far more common to have two separate methods.
Benedict Cohen
Thanks! the NSNumber wrapper works great, and it makes it much easier now since I can potentially send strings to the onscreen text field as well as integers. I didn't even have to separate the NSObject types since my code can handle both.
SeniorShizzle