开发者

Instance variable does not retain its value

I'm learning Objective-C right now and in order to practice I wrote a simple random maze generator for OS X, which works 开发者_如何学Pythonfine. Next I tried to add some more interaction with buttons, but I'm having trouble with the instance variables as they don't retain the value I assign them. I have come across multiple questions about the same problem, but the solutions to those haven't solved my problem. I also tested if the same problem persists in a simplified version of the program, which it does.

I guess I'm doing something wrong, but I don't know what. Here's what I did:

  • Created a new project
  • Added a subclass of NSView called "TestClass"
  • Added a view with class TestClass in the window in MainMenu.xib
  • Added an object for TestClass in MainMenu.xib
  • Added a button to the view and set its tag to 1
  • Added the following code to TestClass.h and TestClass.m and connected the button to it:

TestClass.h: #import

@interface TestClass : NSView
{
    NSNumber *number;
    NSButton *test;
}

@property (nonatomic, retain) NSNumber *number;


@property (assign) IBOutlet NSButton *test;

- (IBAction)testing:(id)sender;

@end

TestClass.m: #import "TestClass.h"

@implementation TestClass

@synthesize number;
@synthesize test;

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (IBAction)testing:(id)sender
{
    self.number = [[NSNumber numberWithLong:[sender tag]] retain];
}

- (void) drawRect:(NSRect)dirtyRect
{
    NSLog(@"%@", number);
}

@end

Whenever I press the button, NSLog just returns null several times.

I normally figure out everything by myself (eventually...), but this time it's really driving me insane, so is there anyone who can help me?


Put the NSLog in testing:, or just put a breakpoint there and see what's stored in number.

Note that self.number = [[NSNumber numberWithLong:[sender tag]] retain]; is double-retaining the NSNumber object (which is wrong), but that shouldn't cause any immediate error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜