问题描述
我有一个属性:
@property (strong, nonatomic) NSWindow *window;
在我的实现中,我有两种方法,分别是start和stop.
And in my implementation, I have two methods, start and stop.
启动功能会像这样(部分代码)创建一个新窗口:
The start function creates a new window like so (partial code) :
_window = [[NSWindow alloc] initWithContentRect:screenRect
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
停止功能将关闭窗口,如下所示:
The stop function closes the window like so:
[_window orderOut:self];
[_window close];
//_window = nil;
但是,当我第二次执行启动功能(启动,然后停止,然后再次启动)时,出现EXC_BAD_ACCESS错误.
However, I get an EXC_BAD_ACCESS error when I execute the start function for the second time (start, then stop, then start again).
这发生在NSWindow的alloc语句上.
This happens on the NSWindow alloc statement.
我该怎么做才能确保正确创建一个新窗口?
What do I need to do to make sure that a new window is created correctly?
经过更多测试,看来该错误与alloc init调用无关.如果在此之前添加以下行:
NSLog(@"%@", _window);
在第一次调用start时,将导致输出"null",然后在调用stop()和新的start调用之后,我将在NSLog行上收到EXC_BAD_ACCESS错误.
On first call to start, this will result in output "null", then after the call to stop() and the new call to start, I will get a EXC_BAD_ACCESS error on the NSLog line.
即使只是设置_window = nil;在stop方法中(调用[_window close];之后)会导致严重的访问错误.
Even just setting _window = nil; in the stop method (after calling [_window close];) causes a bad access error.
推荐答案
您需要添加什么:
_window = [[NSWindow alloc] initWithContentRect:screenRect
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[_window setReleasedWhenClosed:NO];
出现EXC_BAD_ACCESS错误的原因是该窗口设置为在关闭时被释放,释放消息为当前事件完成后发送给该对象.对于NSWindow对象,默认值是在关闭时释放.
The reason you got an EXC_BAD_ACCESS error isthe window is set to be released when closed, a release message is sent to the object after the current event is completed. For an NSWindow object, the default is to be released on closing.
这篇关于可可ARC:从内存中删除窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!