Objective C将数字转换为NSNumber [英] Objective C convert number to NSNumber

查看:94
本文介绍了Objective C将数字转换为NSNumber的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不能令编译器满意,而投射应该像c一样工作,因为我可以在这里阅读如何在Objective-C中投射对象

Why this doesn't please the compiler whereas casting is supposed to work like in c asI can read here How to cast an object in Objective-C

[p setAge:(NSNumber*)10];

其中

- (NSNumber*) age {
    return _age;
}
- (void) setAge: (NSNumber*)input {
    [_age autorelease];
    _age = [input retain];
}


推荐答案

在某种对称中您的之前的问题 NSNumber 是一种对象类型。您需要通过方法调用来创建它,例如:

In a sort of symmetry with your earlier question, NSNumber is an object type. You need to create it via a method invocation such as:

[p setAge:[NSNumber numberWithInt:10]];

您当前的代码只是试图转换任意整数 10 指针从不这样做:如果编译器没有警告你,那么你会尝试在内存位置访问一些完全不合适的字节 10 好像它们是 NSNumber 对象,它们不是。做这些事情会导致眼泪。

Your current code is attempting simply to cast the arbitrary integer 10 to a pointer. Never do this: if the compiler didn't warn you about it, you would then be trying to access some completely inappropriate bytes at memory location 10 as if they were an NSNumber object, which they wouldn't be. Doing that stuff leads to tears.

哦,只是为了抢占下一个明显的问题,请记住,如果你想在中使用该值NSNumber 对象,您还需要通过方法调用来获取,例如:

Oh, and just to preempt the next obvious issues, remember that if you want to use the value in an NSNumber object, you need to get at that via method calls too, eg:

if ( [[p age] intValue] < 18 )
    ...

NSNumber 是不可变的,我认为它的实现使得相同的值被映射到同一个对象。所以它可能可能为了消除 NSNumber 对象之间价值相等的直接指针比较。但是请不要,因为那将是对实施的不恰当依赖细节。请改用 isEqual 。)

(NSNumber is immutable, and I think it is implemented such that identical values are mapped to the same object. So it is probably possible to get away with direct pointer comparisons for value equality between NSNumber objects. But please don't, because that would be an inappropriate reliance on an implementation detail. Use isEqual instead.)

这篇关于Objective C将数字转换为NSNumber的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆