为什么 - NSWindowcontroller的不同实例如何共享相同的变量?

时间:2013-02-12 19:17:38

标签: objective-c cocoa automatic-ref-counting nstimer nswindowcontroller

有一个nib文件,我正在创建具有不同上下文的不同窗口实例,所有控件都正常工作,除了定时器和定时器触发的变量看起来与所有窗口共享。这就是我创建窗口实例的方式。

#import <Cocoa/Cocoa.h>
#import "MYWindow.h"
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
}
@property (strong) MYWindow *pickerWindow;

-

#import "AppDelegate.h"
@implementation AppDelegate
-(IBAction)newWindow:(id)sender
{
    myWindow = [[MYWindow alloc] initWithWindowNibName:@"MYWindowNIB"];
    [myWindow showWindow:self];
}

我也遇到ARC的问题,当我打开一个窗口的新实例时,前一个版本立即释放,即使我声明它在属性中,这就是为什么用标志-fno-objc编译AppDelegate的原因-弧。否则,因为我说什么,我立即发布Windows版本。 XCode 4.6

修改

int i = 0;
-(void)windowDidLoad
{
    timerMoveOutNavBar = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countUP) userInfo:nil repeats:YES];
}

-(void)countUP
{
    [text setStringValue:[NSString stringWithFormat:@"%d", i]];
    i++;
}

2 个答案:

答案 0 :(得分:0)

我找到了解决方案,你必须将变量和所有其他对象声明为私有。

@private
    int i;

答案 1 :(得分:-1)

“共享相同的变量”是什么意思?您可以拥有一个所有窗口控制器继承的超类,并且它们都将具有您在超类中创建的属性和方法,如果这就是您所说的。

对于正在发布的窗口,您是否在IB中选中了“关闭后释放”框?如果是这样,请取消选中该框。

编辑后

问题与初始化int变量“i”的方式有关。通过将它放在方法之外,您将其声明为所有实例都将看到的全局变量。您应该创建一个ivar并在创建计时器时将其值设置为零:

@implementation MyWindowController {
   IBOutlet NSTextField *text;
    int i;
}


- (void)windowDidLoad {
    [super windowDidLoad];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countUP:) userInfo:nil repeats:YES];
    i = 0;
}

-(void)countUP:(NSTimer *) timer {
    [text setStringValue:[NSString stringWithFormat:@"%d", i]];
    i++;
    if (i== 50) [timer invalidate];
}

请注意,我在选择器名称中添加了冒号 - 使用计时器,计时器将自身作为参数传递给其选择器,因此您可以像我一样引用它来使其无效。但是通过将计时器分配给ivar或属性(在您的情况下为timerMoveOutNavBar),可以按照您的方式执行此操作。