xcode 将浮点值转换为 id。我怎样才能做到这一点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8413383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:41:52  来源:igfitidea点击:

Convert Float Value To id. How can i do this?

objective-cxcodefloating-point

提问by Yusuf OZKAN

Possible Duplicate:
How can I store a float value in an NSArray?

可能的重复:
如何在 NSArray 中存储浮点值?

it wants id value but my variable is float. and i want to import tmpValue array 1. object. How Can i do this?

它需要 id 值,但我的变量是浮点数。我想导入 tmpValue 数组 1. 对象。我怎样才能做到这一点?

tmpToplam =  tmpToplam + ([[self.closeData objectAtIndex:i]floatValue] - tmpToplam)* expCarpan;


            [tmpValue replaceObjectAtIndex:1 withObject:tmpToplam]; 

回答by Marko

You probably want to wrap your floats in NSNumber, as id is just a pointer to "any Objective-C object" and NSNumber is the appropriate Object-C class to wrap numbers:

你可能想把你的浮点数包裹在 NSNumber 中,因为 id 只是一个指向“任何 Objective-C 对象”的指针,而 NSNumber 是合适的 Object-C 类来包裹数字:

float a = 2.0;
float b = 3.0;
NSNumber *aNumber = [NSNumber numberWithFloat:a];
NSNumber *bNumber = [NSNumber numberWithFloat:b];
NSArray *array = [NSArray arrayWithObjects:aNumber, bNumber, nil];

回答by jbat100

idis a pointer to an objective c object, in the case of cocoa generally an NSObject, so you need to wrap your float in an NSNumber(which inherits from NSObject). NSNumbercan handle many other primitive types.

id是指向目标 c 对象的指针,在可可的情况下通常是 an NSObject,因此您需要将浮点数包装在 an NSNumber(继承自NSObject)中。NSNumber可以处理许多其他原始类型。

回答by utsabiem

Why don't you convert tmpToplam into string using NSString StringWithFormat ? Actually in an array, you need to put an object and float is not considered object. String is, of course, an object.

为什么不使用 NSString StringWithFormat 将 tmpToplam 转换为字符串?实际上在数组中,您需要放置一个对象,而 float 不被视为对象。字符串当然是一个对象。