使用Objective-C设置NSTextField的标签stringValue,属性IBOutlet NSTextField存在于单独的类中

时间:2013-08-07 05:16:01

标签: objective-c cocoa nstextfield iboutlet

首先,我是一个非常新的(大约2.5周)在Objective-C中进行编程,甚至更新为OS X cocoa应用程序编写代码。我试图在AppDelegate.m中设置NSTextField标签的值,其IBOutlet属性存在于另一个类中。我正在尝试将其放在AppDelegate.m的- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{}部分中,以便在加载MainMenu.xib文件并在屏幕上显示之前设置NSTextField的值。以下是我到目前为止的以下代码:

AppDelegate.m:

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{    
//  Get Physical memory in MB
    MemoryMonitoring *physicalMemoryObj = [[MemoryMonitoring alloc]init];
    unsigned long long physicalMemoryValue = [physicalMemoryObj getPhysicalMemoryValue];

//  Set the labels on the slider
    RamdiskSize *sizeLabels = [[RamdiskSize alloc]init];
    NSString *maxValue = [[NSString alloc] initWithFormat:@"%lluGB",(physicalMemoryValue / 1024)];

//  This line is not doing what I had expected
[sizeLabels.textLabelSizeMax setStringValue:maxValue];

}
@end

MemoryMonitoring.h:

#import <Foundation/Foundation.h>
@interface MemoryMonitoring : NSObject

-(unsigned long long)getPhysicalMemoryValue;

@end

MemoryMonitoring.m:

#import "MemoryMonitoring.h"

@implementation MemoryMonitoring

-(unsigned long long)getPhysicalMemoryValue{
    NSProcessInfo *pinfo = [NSProcessInfo processInfo];
    return ([pinfo physicalMemory] /1024/1024);
}

@end

RamdiskSize.h:

#import <Foundation/Foundation.h>

@interface RamdiskSize : NSObject
@property (weak) IBOutlet NSTextField *textLabelSizeMax;

@end

RamdiskSize.m:

#import "RamdiskSize.h"
#import "MemoryMonitoring.h"

@implementation RamdiskSize
@synthesize textLabelSizeMax;

@end

正如我在AppDelegate.m中所评论的那样,有问题的行是[sizeLabels.textLabelSizeMax setStringValue:maxValue];。我唯一的其他编程经验来自VBScript,据我所知,Objective-C使用点语法来访问属性,所以这一行似乎没有按照我的预期去做。如果有人能说明如何正确地完成这项工作,我将非常感谢您的投入。

1 个答案:

答案 0 :(得分:0)

需要有一个UIViewController或一个子类。 textField必须是以视图控制器视图为根的视图层次结构的一部分。也许从单个视图应用程序模板开始,并将文本字段添加到该视图。

然后当该视图控制器看到viewWillAppear fire时,它可以向MemoryMonitoring类询问该值并继续设置它自己的文本字段。

您走在正确轨道上的一个好兆头就是您需要在应用代理代码中添加几乎任何内容。