2

如何从其他实现文件的类方法中访问实例变量的属性(标题、状态、...)?我尝试了@synthesize,但我无法让它工作。更准确地说;我需要访问 NSWindowController 类的 IBOutlets。

4

3 回答 3

1

首先,你应该先阅读这一章。

Objective-C 编程语言简介

你到底想知道什么。显然,没有实例就不能访问实例变量。类方法是无需任何对象实例即可访问的静态方法(消息)。你能准确地说出你的问题大卫吗?

于 2010-04-01T13:01:48.370 回答
0

好的,那么你只需要在你的类接口中声明你的属性。您的实例变量以 IBOutlet 为前缀,表示必须使用 nib 设置它们。也许你已经知道所有这些东西了。在那种情况下很抱歉。

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - -    
  MyClass.h file
*/
@interface MyClass
{

// instance vars
IBOutlet NSString *title; // Do you have this ? Should be bind in IB.
}

// and this to declare the accessors as public methods
@property (nonatomic, retain) NSString *title;

/*
other methods signature declaration
*/
@end
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - -    
  MyClass.m file
*/
@implementation MyClass

@synthesize title; // allow to generate the accessors of your property

/*
methods implementation here
*/

@end

如果您实例化您的类,只需调用访问器 [myObjectOfMyClass 标题]。也许看到单例设计模式是最常用和最有用的模式之一,可以轻松检索必须唯一的对象实例。 你的 Objective-C 单例是什么样的?

文森特·兹格布

于 2010-04-01T18:31:22.377 回答
0

我通常使用我的 appcontroller 作为我需要在所有课程中访问的东西的中介……假设您的 appcontroller 也是您的应用程序的委托。从任何课程我都可以使用 [NSApp delegate] 访问我的 appcontroller(应用程序委托)。

考虑到这一点,我确保我的 appcontroller 实例化了诸如窗口控制器之类的东西。然后,如果我需要访问窗口控制器,我会在我的 appcontroller 中为它创建一个实例变量,然后为该实例变量创建一个访问器方法。例如:

在 appcontroller.h 中:

MyWindowController *windowController;
@property (readonly) MyWindowController *windowController;

在 appcontroller.m 中:

@synthesize windowController;

然后从任何类我可以使用以下方法访问窗口控制器的该实例:

MyWindowController *windowController = [[NSApp delegate] windowController];
于 2010-04-01T20:17:26.010 回答