Initialize NSArray with floats?

后端 未结 7 2140
你的背包
你的背包 2021-02-12 19:54

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

NSArray *fatArray = [NSArray arrayWithObjects:
                    [NSNumber numberWithFloat:6.9]         


        
7条回答
  •  春和景丽
    2021-02-12 20:40

    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.

    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.

提交回复
热议问题