0

我想实现这样的事情,但由于 id 导致我在 add 中出错!

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];

我想添加 rgb 而不是 id ?

4

1 回答 1

3

您只能将指向对象实例的指针添加到NSMutableArray

您可以使用NSDictionary或创建自己的子类NSObject来包装 3 个值。

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

[rgbarray addObject:rgbDictionary];

检索值

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

我实际上会使用子类方法。由于您尝试使用 C 数组为您的值编写代码,因此该NSDictionary方法将使您摆脱错误。

于 2012-05-09T06:07:43.383 回答