我正在尝试从不同的类设置NSTextField的文本..
这就是我所拥有的:
Preferences.h
@interface Preferences : NSObject
{
IBOutlet NSTextField *selectionPointX;
}
@property (nonatomic, unsafe_unretained) IBOutlet NSTextField *dateTimeFormatPreview;
- (void)getSelection:(NSPoint)point :(NSSize)size;
@end
Preferences.m(仅限所需内容)
#import "Preferences.h"
@implementation Preferences
NSUserDefaults *userDefaults = nil;
int cPx;
int cPy;
int cSw;
int cSh;
- (void)getSelection:(NSPoint)point :(NSSize)size{
cPx = (int) point.x;
cPy = (int) point.y;
cSw = (int) size.width;
cSh = (int) size.height;
[self saveSelection];
}
- (void)saveSelection{
NSPoint p;
p.x = cPx;
p.y = cPy;
NSSize s;
s.width = cSw;
s.height = cSh;
[userDefaults setObject:NSStringFromPoint(p) forKey:@"selectionPoint"];
NSLog(@"Saved Window Position: X: %i Y: %i", cPx, cPy);
[userDefaults setObject:NSStringFromSize(s) forKey:@"selectionSize"];
NSLog(@"Saved Window Size: W: %i H: %i", cSw, cSh);
[userDefaults synchronize];
[selectionPointX setIntegerValue:cPx]; // selectionPointX is nil
}
@end
我从另一个类调用getSelection
,将值传递给它。
在Interface Builder中,我有一个类Preferences
的NSObject,从中我已将Outlet连接到控制器。
但是,当调试selectionPointX
为nil
并因此不更新我的TextField时。
我是Objective-c的新手,所以我可能做错了。 我搜索了很多但找不到解决方案。
感谢任何帮助,谢谢。
编辑:我想我发现了这个问题。因为我从另一个类调用该方法,所以我创建了该类的另一个实例,因此没有连接所有连接。
我做到了:
Preferences *prefs = [[Preferences alloc] init];
[prefs getSelection:(NSPoint)wPos :(NSSize)wSize];
如何调用相同的方法,但使用XIB加载的当前Preferences
实例?
答案 0 :(得分:0)
我有一个LocalSettingsController,它类似于你想要的东西。为了始终使用相同的Preferences实例实现Singleton模式。这是代码:
@implementation LocalSettingsController
+ (id)alloc
{
return self.sharedSettings;
}
+ (id)allocWithZone: (NSZone *)zone
{
return self.sharedSettings;
}
+ (instancetype)sharedSettings
{
static LocalSettingsController* singleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[self localAlloc] localInit];
});
return singleton;
}
- (id)init
{
return self;
}
+ (id)localAlloc
{
return [super allocWithZone: NULL];
}
- (id)localInit
{
return [super init];
}
在代码中,您可以使用sharedSettings
成员,在IB中,您可以在xib中放置一个NSObject,并将其实例类型更改为LocalSettingsController(或在您的首选项中)。