簡體   English   中英

可可NSTextField

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM