0

我在书中找到的项目有问题。点击屏幕时,项目会弹出不同的形状。我的问题是它创建了一个异常,我相信问题是 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();
    }
}

形状.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

形状.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

4

1 回答 1

0

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

@property (nonatomic, retain) UIColor *color;

& 然后分配

shape.color=[self makeRandomColor]; 
于 2013-01-26T05:38:35.363 回答