[英]Cocoa NSTextField
我在不同类的NSTExtField中访问值时遇到问题,这是代码:
AppDelegate.h
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSTextField *numberOfPhrases;
@end
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize numberOfPhrases;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog(@"%@",[numberOfPhrases stringValue]);
}
TestClass.h
@interface TestClass : NSObject
- (IBAction)doSomething:(id)sender;
@end
TestClass.m
@implementation TestClass
- (IBAction)doSomething:(id)sender {
NSLog(@"%@",[numberOfPhrases stringValue]); ?????????
}
如果没有链接,显然您不能访问另一个类中的文本字段值。
要访问该文本字段的值,您需要在此类中为其添加一个IBOutlet或将一个IBOutlet分配给AppDelegate,以便您可以访问其属性。
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;
@end
TestClass.m
@implementation TestClass : NSObject
- (IBAction)doSomething:(id)sender
{
[[appDel numberOfPhrases]stringValue]; //get the string value in text field
}
@end
您唯一缺少的是对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];
调用实例[[AppDelegate alloc] init];
您需要将NSTextField
链接到Interface Builder do:Something -> TestClass
和引用出口 numberOfPhrases -> AppDelegate
的已发送动作 。
输出 :
2014-01-21 23:32:56.499 test[6236:303] Wonders Never Cease
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.