Search code examples
objective-cparametersprimitive

Objective-C Method Parameters Problem


I'm attempting to define an extremely simple utility method that will save me from having to use a calculator to define RGB values as percentages. When I look into Apple's sample code called "QuartzCache", in the DrawView.m file, line 96, I see this:

float whiteColor[4] = {1, 1, 1, 1};

However, when I attempt to created a method like the following, the compiler hates me. A half-hour of intensive Googling has not produced any help.

 +(float[])percentagesRGBArray:(float[])rgbArray{

        float red = rgbArray[0];
        float green = rgbArray[1];
        float blue = rgbArray[2];
        float alpha = rgbArray[3];
        red = red/255;
        green = green/255;
        blue = blue/255;
        alpha = alpha;
        float percentagesRGBArray[4] = {red, green, blue, alpha};


        return  percentagesRGBArray;
    }

What is the proper way to define such a method? What am I doing wrong here?


Solution

  • Define a struct that contains all of the components, or wrap up each individual component in an NSNumber. Alternatively, use an NSColor instance to contain your colour components.

    • struct way:

      typedef struct
      {
          float red;
          float green;
          float blue;
          float alpha;
      } MyColor;
      
      - (MyColor) percentagesRGBArray:(MyColor) incoming
      {
          MyColor result;
          result.red = incoming.red / 255;
          result.green = incoming.green / 255;
          result.blue = incoming.blue / 255;
          result.alpha = incoming.alpha;
          return result;
      }
      
    • NSNumber way:

      - (NSArray *) percentagesRGBArray:(float[]) rgbArray
      {
          NSNumber *red = [NSNumber numberWithFloat:rgbArray[0] / 255];
          NSNumber *green = [NSNumber numberWithFloat:rgbArray[1] / 255];
          NSNumber *blue = [NSNumber numberWithFloat:rgbArray[2] / 255];
          NSNumber *alpha = [NSNumber numberWithFloat:rgbArray[3]];
      
          return [NSArray arrayWithObjects:red, green, blue, alpha, nil];
      }
      
    • NSColor way:

      - (NSColor *) percentagesRGBArray:(float[]) rgbArray
      {
          CGFloat red = rgbArray[0] / 255;
          CGFloat green = rgbArray[1] / 255;
          CGFloat blue = rgbArray[2] / 255;
          CGFloat alpha = rgbArray[3];
      
          return [NSColor colorWithDeviceRed:red
                                       green:green
                                        blue:blue
                                       alpha:alpha];
      }