0

I want to implement thing like that but i get error in add because of id !!!

NSMutableArray *rgbarray = [[NSMutableArray alloc] init];
 NSInteger rgb[3];
            const CGFloat *components = CGColorGetComponents(cgcolor);
            CGFloat cgred = components[0];
            CGFloat cggreen = components[1];
            CGFloat cgblue = components[2];
            rgb[0] = cgred;
            rgb[1] = cggreen;
            rgb[2] = cgblue;

            [rgbarray addObject:rgb];

i want to add rgb instead of id ?

1

1 Answer 1

3

You can only add pointers to instances of objects into NSMutableArray

You can use a NSDictionary or create your own subclass of NSObject to wrap the 3 values.

NSDictionary * rgbDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:cgred], @"cgred", [NSNumber numberWithFloat:cggreen], @"cggreen", [NSNumber numberWithFloat:cgblue], @"cgblue", nil];

[rgbarray addObject:rgbDictionary];

To retrieve the values

NSDictionary * rgbDictionary = [rgbArray objectAtIndex:0];
CGFloat cgred = [[rgbDictionary objectForKey:@"cgred"] floatValue];
CGFloat cggreen = [[rgbDictionary objectForKey:@"cggreen"] floatValue];
CGFloat cgblue = [[rgbDictionary objectForKey:@"cgblue"] floatValue];

I would actually use the subclass approach. Since you were trying to code with a C array for your values, the NSDictionary approach will get you past the error.

Sign up to request clarification or add additional context in comments.

5 Comments

You really should just be using a C-array here, as NSArray w/ NSNumbers are incredibly slow compared to a c array.
I got this error when i tried to retrieve them back Initializing 'CGFloat' (aka 'float') with an expression of incompatible type 'id';
@salamonti I had typed the code into the browser only. I forgot to access the floatValue. Since we populated the NSDictionary with NSNumbers, you need to use the floatValue property to access the primitive float from the NSNumber
Is it require any import file ?
@salamonti the adjusted code doesn't require an import. Using the method floatValue as a opposed to the property. It is easier to get it to compile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.