简体   繁体   English

将NSObject转换为NSNumber

[英]Convert NSObject to NSNumber

How to convert object of type NSObject to NSNumber in Objective-C? 如何在Objective-C中将NSObject类型的对象转换为NSNumber

In Android I do this: 在Android中,我这样做:

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

But how I can convert value in Objective-C? 但是如何在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. 弄清您的错误后,Objective-C-ese解决方案是使用id作为参数类型。 The type id means "any object type" and the compiler allows you to call any method. 类型id表示“任何对象类型”,编译器允许您调用任何方法。 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: : 您可以通过使用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];
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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