我想知道是否可以將NSWindow的引用傳遞給自定義對象,然後使用該對象爲該按鈕添加NSButton和相關的動作/選擇器。我可以將NSWindow的引用傳遞給自定義對象,並使用該對象添加NSButton和Action?
我嘗試這個時似乎遇到問題。當我運行示例程序並點擊按鈕,會出現以下運行時錯誤: 線程1:EXC_BAD_ACCESS(代碼= 1,地址=爲0x18)
這裏是我的代碼:
// AppDelegate.h
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@end
// AppDelegate.m
#import "AppDelegate.h"
#import "CustomObject.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
CustomObject *test = [[CustomObject alloc]init];
[test createButton:_window];
}
@end
// CustomObject.h
#import <Foundation/Foundation.h>
@interface CustomObject : NSObject
{
int test;
NSButton *testButton;
}
- (IBAction)pressCustomButton:(id)sender;
-(void)createButton:(NSWindow*)win;
@end
// CustomObject.m
#import "CustomObject.h"
@implementation CustomObject
-(IBAction)pressCustomButton:(id)sender
{
NSLog(@"pressCustomButton");
}
-(void)createButton:(NSWindow*)win
{
testButton = [[NSButton alloc] initWithFrame:NSMakeRect(100, 100, 200, 50)];
[[win contentView] addSubview: testButton];
[testButton setTitle: @"Button title!"];
[testButton setButtonType:NSMomentaryLightButton]; //Set what type button You want
[testButton setBezelStyle:NSRoundedBezelStyle]; //Set what style You want
[testButton setTarget:self];
[testButton setAction:@selector(pressCustomButton:)];
}
@end