简体   繁体   中英

Convert NSObject to NSNumber

How to convert object of type NSObject to NSNumber in Objective-C?

In Android I do this:

if(value instanceof Integer){
   intValue = (Integer)value;
}

But how I can convert value in Objective-C?

My code:

-(void)changeWithValue:(NSObject*)value{
     if([value isKindOfClass:[NSNumber class]])
          float floatValue = [value floatValue];
 }

But it is not working :(

Help me please. Thanks

After clarification of what your error was the Objective-C-ese solution is to use id as the parameter type. The type id means "any object type" and the compiler allows you to call any method. So you would have code along the lines of:

- (void)changeWithValue:(id)value
{
   if([value isKindOfClass:[NSNumber class]])
   {
      float floatValue = [value floatValue];
      ...
   }
   else
   {
      // handle not an `NSNumber`
   }
}

You can make it more general for testing for the method rather than the type by using respondsToSelector: :

- (void)changeWithValue:(id)value
{
   if([value respondsToSelector:@selector(floatValue)])
   {
      float floatValue = [value floatValue];
      ...
   }
   else
   {
      // handle case where value does not support floatValue
   }
}

HTH

Have you try this

-(void)changeWithValue:(NSObject*)value{
 if([value isKindOfClass:[NSNumber class]])
      NSNumber *num = (NSNumber*)value;
      float floatValue = [num floatValue];
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM