views:

116

answers:

2

Hi all!

Given

@interface Canvas:NSView {        
    NSNumber * currentToolType; 
    ...
}

declared in my .h file and in the .m file

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
     currentToolType=[[NSNumber alloc]initWithInt:1];
    }
    return self;
}

and further down

-(void)mouseUp:(NSEvent *)event
{
   NSLog(@"tool value in event: %d",[currentToolType intValue]);
   //rest of code
}

-(NSBezzierPath *)drawPath:(NSRect)aRect
{
   NSLog(@"tool value in draw: %d",[currentToolType intValue]);

//rest of drawPath method code that uses the value of currentToolType in a switch statment

}

-(IBAction)selectToolOne:(id)sender
{
   [currentToolType release];
   [currentToolType = [[NSNumber alloc]initWithInt:0];
}

-(IBAction)selectToolTwo:(id)sender
{
   [currentToolType release];
   [currentToolType = [[NSNumber alloc]initWithInt:1];
}

The action methods are the only place where currentToolType is changed. But, for some reason, it seems to be a different instance of currentToolType in the mouseUp. I did not write (or synthesize) accessors for the var as it is used only by itself. I noticed that initWithFrame is called twice - I'm assuming it's for the parent window and the NSView?

What am I missing?
THANKS!
This is an XCode generated Document based app using COCOA and Obj-C. I'm new at both.

A: 

You've probably run in to a special case: NSNumber could have cached instances to represent commonly-used numbers.

Two observations, though:

  • You're wasting a whole lot of memory using NSNumber when you could be simply using NSIntegers or maybe an old-fashioned enumerated type, completely avoiding the object overhead.
  • You never actually showed your code for when you look at the instances of NSNumber; without it, there's not really enough information here to answer your question.
Jim Puls
Thanks Jim. I used a simple int - same deal. You asked about how it's used. Exactly the same as the NSLog statments. e.g. switch (currentToolType intValue]{case 0:....etc.
+2  A: 

You mention that initWithFrame: is called twice. Your initWithFrame: should only be called once (unless you happen to have two Canvas views).

Is it possible you have the Canvas view in your nib/xib file and are also creating another in code (with alloc/initWithFrame:)?

In which case you have two Canvas objects. You probably have one hooked up to your controls and the other one is in the window (and thus responding to the mouseUp: and it is giving you the same value every time).

If you have the Canvas view setup in IB, you can fix this problem by removing your code that is creating the second one.

Nathan Kinsinger