我正在尝试解决一个更大的问题,并且我提示 ARC 显然太早地将 View 发布到我的 NSViewController 了。我想:)所以我创建了一个简单的应用程序来重建情况。
我有一个简单的 ARC Cocoa 应用程序。在 MainMenu.xib
的窗口中,我将一个 Custom View
连接到声明的 @property (strong) IBOutlet NSView *theView;
在AppDelegate.h
在 AppDelegate.m
中,我综合该属性,然后调用以下内容:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
TestViewController *tvc = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];
[_theView addSubview:[tvc view]];
}
TestViewController
显示在自定义 View
中 - 没问题。它包含一个 NSButton。它连接到一个名为 -(IBAction)btnPressed:(id)sender
的方法和一个也连接为 IBOutlet
的 NSTextView。
在TestViewController.h
中我声明:
@property (nonatomic, strong) IBOutlet NSTextField *textField;
@property (nonatomic, strong) NSString *theString;
-(IBAction)btnPressed:(id)sender;
然后在 TestViewController.m
中我执行
@synthesize theString = _theString;
@synthesize textField = _textField;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Initialization code here.
_theString = @"Hello World";
}
return self;
}
-(IBAction)btnPressed:(id)sender
{
[_textField setStringValue:_theString];
}
当我运行应用程序并按下按钮时,它崩溃了。如果我检查僵尸,我会收到以下信息:
# Address Category Event Type RefCt Timestamp Size Responsible Library Responsible Caller
0 0x7f97a3047560 TestViewController Malloc 1 00:00.652.631 128 TestARC -[AppDelegate applicationDidFinishLaunching:]
1 0x7f97a3047560 TestViewController Retain 2 00:00.653.088 0 TestARC -[TestViewController initWithNibName:bundle:]
2 0x7f97a3047560 TestViewController Release 1 00:00.653.089 0 TestARC -[TestViewController initWithNibName:bundle:]
3 0x7f97a3047560 TestViewController Retain 2 00:00.653.912 0 AppKit -[NSNib instantiateNibWithOwner:topLevelObjects:]
4 0x7f97a3047560 TestViewController Release 1 00:00.658.831 0 AppKit -[NSNib instantiateNibWithOwner:topLevelObjects:]
5 0x7f97a3047560 TestViewController Release 0 00:00.662.377 0 Foundation -[NSNotificationCenter postNotificationName:object:userInfo:]
6 0x7f97a3047560 TestViewController Zombie -1 00:01.951.377 0 AppKit -[NSApplication sendAction:to:from:]
我做错了什么? 谢谢
最佳答案
添加一个属性来保存 View Controller 。您的 Controller 当前没有任何东西可以使其在分配它的方法结束后保持事件状态。
添加:
@property (strong) TestViewController *tvc;
修改:
self.tvc = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];
(我很好奇......如果您想要的只是它包含的 View ,您认为创建 View Controller 的意义是什么?)
<小时/>关于一般方法,似乎这是应该使用容器 View Controller 实现的更正确的行为。该机制允许多个 View Controller 以有组织的方式共享屏幕。
关于objective-c - ARC 似乎正在释放我的 NSViewController 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11700530/