views:

86

answers:

1

I'm trying to build a UIColor from a comma-delimited list of values for RGB, which is "0.45,0.53,0.65", represented here by the colorConfig object...

NSScanner *scanner = [NSScanner scannerWithString:colorConfig];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n, "]];
float red, green, blue;
return [UIColor colorWithRed:[scanner scanFloat:&red] green:[scanner scanFloat:&green] blue:[scanner scanFloat:&blue] alpha:1];

But my color is always coming back as black. So I logged the values to my console and I'm seeing Red = -1.988804, Green = -1.988800, Blue = -1.988796

What am I doing wrong?

+2  A: 

Your problem is that the scanFloat: method does not return a float. It returns a BOOL that tells you whether or not the scanner actually read a float (if you cared to do any kind of validation on your colorConfig string, for example). Instead, the scanFloat: method reads the float into the variable that you supply (in this case red, green and blue). You read garbage when you log these variables because they are on the stack and will take whatever garbage is there, since you didn't initialize them.

Using what you have, this should actually return a color and log if the scan was valid:

NSScanner *scanner = [NSScanner scannerWithString:colorConfig];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n, "]];
float red, green, blue;
NSLog(@"Valid red scan: %@", [scanner scanFloat:&red]?@"YES":@"NO");
NSLog(@"Valid green scan: %@", [scanner scanFloat:&green]?@"YES":@"NO");
NSLog(@"Valid blue scan: %@", [scanner scanFloat:&blue]?@"YES":@"NO");
return [UIColor colorWithRed:red green:green blue:blue alpha:1];
Jason Coco
Right on! Thank you.
E-Madd