Initialize NSArray with floats?

后端 未结 7 1687
情歌与酒
情歌与酒 2021-02-12 20:05

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:31

    I agree with mouviciel. Since you can't put simple types into an Array this is the way to do it. Looks a bit strange and is a lot of code to write but it is fine.

    0 讨论(0)
  • 2021-02-12 20:32

    Another lazy option is to just use an array of NSStrings and then getting the type of value you are looking for directly from the string.

    Like so:

    NSArray *arrayOfNumbers = [NSArray arrayWithObjects:@"3.12",@"3.2", @"12", @"15", nil];
    float number = [[arrayOfNumbers objectAtIndex:0] floatValue];
    
    0 讨论(0)
  • 2021-02-12 20:35

    If you have a lot of floats to convert, or want to paste them in from a comma separated list, it may be easier to call a function that converts floats into an NSArray instance.

    NSArray*  arrayFromFloats(NSUInteger count, float *floats)
    {
        NSMutableArray* ma = [NSMutableArray arrayWithCapacity:count]; 
        NSUInteger i; 
        for (i=0; i<count; i++) { 
            [ma addObject:[NSNumber numberWithFloat:floats[i]]];
        }
        return (NSArray*)ma; 
    }
    

    Example caller:

    static float floats[] = {1.1, 2.2, 3.3}; 
    NSUInteger count = sizeof(floats)/sizeof(float);
    NSArray* a = arrayFromFloats(count, floats); 
    
    0 讨论(0)
  • 2021-02-12 20:38

    going off on a slight tangent, if all you want to do is store an array of floats and don't really need the added functionality of an NSArray or NSNumber, then you should also consider just a standard C array:

    float fatArray[] = {6.6, 6.9, 4.7, 6.9};
    
    0 讨论(0)
  • 2021-02-12 20:45

    If you're going to be creating a lot of these arrays with exactly the same number of elements, you could define a FloatArrayFactory class that implements something like:

    + (NSArray *) arrayWithFloat: (float)f;
    + (NSArray *) arrayWithFloat: (float)f1 and: (float)f2;
    + (NSArray *) arrayWithFloat: (float)f1 and: (float)f2 and: (float)f3;
    + (NSArray *) arrayWithFloat: (float)f1 and: (float)f2 and: (float)f3 and: (float)f4;
    

    And if that's too verbose, you could go for the terse and funky look of unnamed parameters:

    + (NSArray *) arr: (float)f1 : (float)f2 : (float)f3;
    

    which you can call like this:

    NSArray *a = [Factory arr: 1.0 :2.0 :3.0 :4.0];
    
    0 讨论(0)
  • 2021-02-12 20:50

    As far as I know, this is a perfectly valid way of putting floats in an NSArray.

    0 讨论(0)
提交回复
热议问题