用浮点数初始化NSArray吗? [英] Initialize NSArray with floats?

查看:71
本文介绍了用浮点数初始化NSArray吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是初始化带有浮动对象的NSArray的有效方法吗?

Is this a valid way to initalize an NSArray with float objects?

NSArray *fatArray = [NSArray arrayWithObjects:
                    [NSNumber numberWithFloat:6.9],
                    [NSNumber numberWithFloat:4.7],
                    [NSNumber numberWithFloat:6.6],
                    [NSNumber numberWithFloat:6.9],nil];

工作正常,感觉不错,只是想确保自己走在正确的轨道上。

It works and it feels right, just wanted to make sure I was on the right track.

加里

推荐答案

正如mouviciel已经写到的,这就是这样做的方法它。当我写这样的东西时,通常使用一个简单的宏使代码更短:

As mouviciel already wrote, this is the way to do it. When I write something like this I usually make the code shorter using a simple macro:

#define FBOX(x) [NSNumber numberWithFloat:x]

然后,您可以像这样重写代码:

Then you can rewrite the code like this:

NSArray *fatArray = [NSArray arrayWithObjects:
    FBOX(6.9), FBOX(4.7), FBOX(6.6), FBOX(6.9), nil];

宏是邪恶的,但是在这种情况下,宏是如此简单,我会使用它。加上代码不易读,尤其是在宏定义不远的情况下。

Macros are evil, but in this case the macro is so simple I’d use it. Plus the code hurts a bit less to read, especially if the macro definition is not far.

如果您编写了很多这样的代码,则可以使用自定义初始化程序,其可变数量为 float 个参数,但是在结束参数列表时会出现问题。您可以先传递浮点数的总数:

If you wrote a lot code like this, you could create a category with a custom initializer with variable number of float arguments, but then there’s a problem ending the argument list. You could pass the total number of floats first:

- (id) initWithFloats: (int) numFloats data: (float) float1, ...;

但是,手工计算参数很容易出错。或者,您可以使用一些标记值(例如零)来标记参数列表的结尾,但这会打开一整套全新的蠕虫,称为浮点比较。

But counting the arguments by hand is prone to error. Or you could use some sentinel value such as zero that would mark the end of the argument list, but this opens a whole new can of worms called floating-point comparison.

请注意,如今您可以简单地编写以下内容:

Please note that nowadays you can simply write the following:

NSArray *list = @[@6.9, @4.7, @6.6, @6.9];

这不是语法梦想成真,但编译器正式支持它,它比先前的解决方案。 有关更多信息,请参阅文档

It’s not a syntax dream come true, but it’s officially supported by the compiler and it’s much better than the previous solutions. See the documentation for more goodness.

这篇关于用浮点数初始化NSArray吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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