属性的值不可接受的类型:

时间:2013-01-26 05:28:57

标签: iphone ios core-data uicolor

我在书中找到的项目有问题。点击屏幕时,项目将弹出不同的形状。我的问题是它创建了一个异常,我相信问题是createShapeAt中的一行:

在NSInvalidArgumentException中,在updateAllShapes中找到属性:所需类型的NSString是它需要的,但输出的类型为UIDeviceRGBColor。我是对的吗?

它有一个例外:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "color"; desired type = NSString; given type = UIDeviceRGBColor; value = UIDeviceRGBColorSpace 0.0980392 0.0705882 0.152941 1.'

代码:

- (void)createShapeAt:(CGPoint)point
{
    Shape *shape = nil;
    int type = arc4random() % 2;
    if (type == 0) {
        shape = [Circle randomInstance:point inContext:self.managedObjectContext];
    }

    else {
        shape = [Polygon randomInstance:point inContext:self.managedObjectContext];
    }

    NSLog(@"Test: %@", [[self makeRandomColor] description]);
    shape.color = [self makeRandomColor]; //This is where the Exception kicks in.
}

- (UIColor *)makeRandomColor
{
    float red = (arc4random() % 256) / 255.0;
    float green = (arc4random() % 256) / 255.0;
    float blue = (arc4random() % 256) / 255.0;

    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

- (void)updateAllShapes
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Shape" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSArray *shapes = [managedObjectContext executeFetchRequest:fetchRequest error:nil];

    for (NSManagedObject *shape in shapes) {
        [shape setValue:[self makeRandomColor] forKey:@"color"];
    }

    NSError *error = nil;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

Shape.h

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class Canvas;

@interface Shape : NSManagedObject

@property (nonatomic, retain) UIColor *color;
@property (nonatomic, retain) NSSet *canvases;
@end

@interface Shape (CoreDataGeneratedAccessors)

- (void)addCanvasesObject:(Canvas *)value;
- (void)removeCanvasesObject:(Canvas *)value;
- (void)addCanvases:(NSSet *)values;
- (void)removeCanvases:(NSSet *)values;
@end

Shape.m

#import "Shape.h"
#import "Canvas.h"

@implementation Shape

@dynamic color;
@dynamic canvases;

@end

控制台:

Test: UIDeviceRGBColorSpace 0.0431373 0.764706 0.223529 1

如何更改这行代码:shape.color = [self makeRandomColor];成为NSString?

编辑:我添加了Shape.h和Shape.m

1 个答案:

答案 0 :(得分:0)

声明如下所示的一个属性,请确保它是retain

@property (nonatomic, retain) UIColor *color;

&安培;分配

shape.color=[self makeRandomColor];