所以我被困了几个小时试图让这个工作。在我的应用程序中,我接收XML数据,通过它解析并以编程方式创建带按钮的图像。但是,当我尝试将字符串转换为CGFloats以便我可以将它们用于按钮坐标时它不起作用。我尝试了一些不同的教程和方法,似乎没有任何工作。您可以在下面的代码中看到我正在尝试多种方式。我知道字符串中有正确的数字,我只是无法转换它。它回来时是Null。救命!提前致谢
$CGFloat buttonViewXvalue = [tempXCorrVariable floatValue];
CGFloat buttonViewYvalue = [tempYCorrVariable floatValue];
buttonViewWidth = [tempWidthCorrVariable floatValue];
buttonViewLength = [tempLengthCorrVariable floatValue];
//The "buttonView" variables are Float Variables and the "temp" Variables are Strings.
NSLog(@"Float X = %@", buttonViewXvalue);
NSLog(@"Float Y = %@", buttonViewYvalue);
NSLog(@"Float Width = %@", buttonViewWidth);
NSLog(@"Float Length = %@", buttonViewLength);
------------------------------------------编辑---- ----------------------------------------
由于良好的反应,我得到了它的工作。原来这只是NSLog的格式化问题。这是新代码:
$CGFloat buttonViewXvalue = [tempXCorrVariable floatValue];
CGFloat buttonViewYvalue = [tempYCorrVariable floatValue];
buttonViewWidth = [tempWidthCorrVariable floatValue];
buttonViewLength = [tempLengthCorrVariable floatValue];
NSLog(@"Float X = %f", buttonViewXvalue);
NSLog(@"Float Y = %f", buttonViewYvalue);
NSLog(@"Float Width = %f", buttonViewWidth);
NSLog(@"Float Length = %f", buttonViewLength);
为了那些想要知道如何将String转换为浮点数或CG浮点数的人的未来参考...只需按照:
CGFloat yourFloatVariable = [stringThatYouWantToConvert floatValue];
确保使用最后一部分“floatValue”上的确切字词。这不是另一个变量或值或任何东西,只需将其放入您的代码中即可。
答案 0 :(得分:3)
你使用错误的格式指定:也许你的浮点数值是正确的,但是使用NSLog替换它会失败。
使用NSLog(@"Float X = %f",buttonViewXvalue);
代替%@
。
仅对NSObject使用%@
。
答案 1 :(得分:3)
我认为您应该花一点时间来审核string format specifiers:
%@ Object
%d, %i signed int
%u unsigned int
%f float/double
%x, %X hexadecimal int
%o octal int
%zu size_t
%p pointer
%e float/double (in scientific notation)
%g float/double (as %f or %e, depending on value)
%s C string (bytes)
%S C string (unichar)
%.*s Pascal string (requires two arguments, pass pstr[0] as the first, pstr+1 as the second)
%c character
%C unichar
%lld long long
%llu unsigned long long
%Lf long double
使用%@
时,会将消息address
发送给NSObject
。如果您使用的是float
,那么它不是NSObject
,因此会出现错误。
要使NSLog
来电有效,您有两种选择,我更喜欢前者:
NSLog(@"Float X = %f", myFloat);
NSLog(@"Float X = %@", [NSNumber numberWithFloat:myFloat]);
第二个是愚蠢的,但强调差异,我希望。