简体   繁体   中英

Cocoa NSTextField

i have a problem with accessing value from the NSTExtField in different class here is the code:

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]); ????????? 


}

You obviously can't access the text field value in another class without a link to it.

To access the text field's value you either need to have one more IBOutlet to it in this class or an IBOutlet to AppDelegate so that you can access its property.

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

OR an another option is to have a IBOutlet of AppDelegate in TestClass (because if you only create a new instance of AppDelegate and not its IBOutlet then a different instance of text field will be created and you will not be able to access the value of your text field)

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

The only thing you're missing is the addition to your TestClass.m file:

#import "TestClass.h"
#import "AppDelegate.h"

@implementation TestClass

- (IBAction)doSomething:(id)sender {

    AppDelegate *theInstance = [[AppDelegate alloc] init];
    [theInstance numberOfPhrases];

}

@end

You need to include the class header of AppDelegate.h in TestClass.m , then you simply call an instance through [[AppDelegate alloc] init]; You'll need to link your NSTextField to the Sent Actions in Interface Builder do:Something -> TestClass and Referencing Outlets numberOfPhrases -> AppDelegate .

Output :

2014-01-21 23:32:56.499 test[6236:303] Wonders Never Cease

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM