Events area
Considering
@interface Canvas:NSView {
NSNumber * currentToolType;
...
}
declared in my .h file and in my .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]);
// the rest of the drawPath method code, which uses the currentToolType value in the toggle state
}
-(IBAction)selectToolOne:(id)sender
{
[currentToolType release];
[currentToolType = [[NSNumber alloc]initWithInt:0];
}
-(IBAction)selectToolTwo:(id)sender
{
[currentToolType release];
[currentToolType = [[NSNumber alloc]initWithInt:1];
}
Action methods are the only place where things change currentToolType
. But for some reason it looks like a different instance currentToolType
in mouseUp
. I have not written (or synthesized) accessors for var as it is only used by itself. I noticed that initWithFrame
it gets called twice - I'm assuming this is for the parent window and NSView?
What am I missing?
THANK!
This is an Xcode based application using COCOA and Obj-C. I am new to both.
You mentioned that initWithFrame: is called twice. Your initWithFrame: only needs to be called once (unless you have two Canvas views).
Is it possible that you have a Canvas view in the nib / xib file and also create another one in code (with alloc / initWithFrame :)?
In this case, you have two Canvas objects. You probably have one attached to your controls and the other in the window (and thus reacting to mouseUp: and it gives you the same value every time).
If you have a Canvas view setup in IB, you can fix this issue by removing the code that creates the second.
source to share
You are probably running into a special case: NSNumber can have cached instances to represent frequently used numbers.
Two observations:
- You are wasting a lot of memory using NSNumber when you can just use NSIntegers, or perhaps an old fashioned enum, avoiding object overhead entirely.
- You have never shown your code when looking at NSNumber; without it, there really isn't enough information to answer your question.
source to share