我在访问不同类中NSTExtField的值时遇到了一个问题,下面是代码:
AppDelegate.h
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSTextField *numberOfPhrases;
@endAppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize numberOfPhrases;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog(@"%@",[numberOfPhrases stringValue]);
}TestClass.h
@interface TestClass : NSObject
- (IBAction)doSomething:(id)sender;
@endTestClass.m
@implementation TestClass
- (IBAction)doSomething:(id)sender {
NSLog(@"%@",[numberOfPhrases stringValue]); ?????????
}发布于 2014-01-22 13:57:09
显然,如果没有指向另一个类的链接,则无法访问其他类中的文本字段值。
要访问文本字段的值,您需要在这个类中再有一个指向它的IBOutlet,或者一个指向AppDelegate的IBOutlet,这样您就可以访问它的属性了。
TestClass.h
@interface TestClass : NSObject
{
IBOutlet NSTextField *numberOfPhrases; // connect it to the new referencing outlet of text field by dragging a NSObject object in your xib and setting its class to "TestClass"
}
- (IBAction)doSomething:(id)sender;
@end或者,另一种选择是在TestClass中使用AppDelegate的IBOutlet (因为如果只创建AppDelegate的新实例,而不创建它的IBOutlet,则将创建文本字段的另一个实例,并且您将无法访问文本字段的值)
TestClass.h
@interface TestClass : NSObject
{
IBOutlet AppDelegate *appDel; // connect in the xib
}
- (IBAction)doSomething:(id)sender;
@endTestClass.m
@implementation TestClass : NSObject
- (IBAction)doSomething:(id)sender
{
[[appDel numberOfPhrases]stringValue]; //get the string value in text field
}
@end发布于 2014-01-22 06:40:10
您唯一缺少的是添加到TestClass.m文件中:
#import "TestClass.h"
#import "AppDelegate.h"
@implementation TestClass
- (IBAction)doSomething:(id)sender {
AppDelegate *theInstance = [[AppDelegate alloc] init];
[theInstance numberOfPhrases];
}
@end您需要在TestClass.m中包含AppDelegate.h的类头,然后您只需通过[[AppDelegate alloc] init];调用一个实例,您将需要将您的NSTextField链接到接口生成器do:Something -> TestClass中的Sent Actions和引用出口 numberOfPhrases -> AppDelegate。
输出
2014-01-21 23:32:56.499 test[6236:303] Wonders Never Ceasehttps://stackoverflow.com/questions/21269406
复制相似问题