views:

21

answers:

1

It's the first time I'm trying to use typedef. Admittedly I don't have a very clear idea of what's going on but my understanding was that the values inside typedef get assigned integers starting with 0. I've tried to use them as integers but I get various warnings and errors. One of them is "[NSCFNumber objectForKey:]: unrecognized selector sent to instance". I don't know how to troubleshoot this. I also haven't written dynamic getters/setters much, so my approach might be wrong. Please help.

// MyView.h

typedef enum 
{
    STYLE_A,
    STYLE_B,
    STYLE_C,
    STYLE_D
} MyShapeStyle;


@interface MyView : UIView
{
    MyShapeStyle shapeStyle;

    CALayer *myLayer;
    MyLayerDelegate *myLayerDelegate;
}

@property (nonatomic) MyShapeStyle shapeStyle;
@property (nonatomic, retain) CALayer *myLayer;
@property (nonatomic, retain) MyLayerDelegate *myLayerDelegate;

@end

// MyView.m

#import "MyView.h"

@implementation MyView

@dynamic shapeStyle;
@synthesize myLayer;
@synthesize myLayerDelegate;


- (id)initWithFrame:(CGRect)frame 
{

    if ((self = [super initWithFrame:frame])) 
    {
        // Initialization code
        MyLayerDelegate *delegate = [[MyLayerDelegate alloc] init];
        self.myLayerDelegate = delegate;


        CALayer *myLayer = [CALayer layer];
        [myLayer setDelegate:delegate];
        [self.layer addSublayer:myLayer];
        self.myLayer = myLayer;
        self.shapeStyle = STYLE_C;

        [delegate release];
    }

    return self;
}

-(MyShapeStyle)shapeStyle
{
    return [[self.myLayer valueForKey:@"style"] integerValue];
}

- (void)setShapeStyle:(MyShapeStyle)style
{
    [self.myLayer setValue:[NSNumber numberWithInt:style] forKey:@"style"];
}

// MyLayerDelegate.m

-(void)drawLayer:(CALayer *)theLayer inContext:(CGContextRef)theContext
{

    int id = [[theLayer valueForKey:@"style"] integerValue];

   if( id == STYLE_A )
   {
   }else if ( id == STYLE_B ){
   }

}
+1  A: 

There is no reason to use valueForKey: in that code; just get/set the various properties directly.

-(MyShapeStyle)shapeStyle
{
    return (MyShapeStyle) self.myLayer.style;
}

There is also no need for the @dynamic in that code. That is only needed if you are going to dynamically generate the methods.

As for why the objectForKey: does-not-respond error, there isn't anything in that code that should trigger that. Could be a retain/release issue or it could be a problem in some other code that you haven't shown.

bbum
Thanks. You're right "valueForKey" was left-over code from a different implementation. I made "style" a property of MyLayerDelegate. However, I have one question regarding that. If I make "style" type "int" everything works. But if I make it type "MyShapeStyle", I get an error "Expected specifier-qualifier-list before 'MyShapeStyle'"?
Anna