开发者

Set value of NSTextField

I am trying to set the value of an NSTextField, but it's not working properly.

I have a button linked to an IBAction, and when I set it 开发者_C百科using self, it works fine:

#import <Foundation/Foundation.h>


@interface TestMessage : NSObject {
     IBOutlet NSTextField *text;
}

- (IBAction) setMessage: (id) controller;
- (void) Message:(NSString *) myMessage;    
@end

#import "TestMessage.h"

@implementation TestMessage

- (IBAction) setMessage: (id) controller {
    // This works
    [self Message:@"Hello"];

    // but this doesn't
    TestMessage * messageTest= [TestMessage new];
    [messageTest Message:@"Hi"];

}
- (void) Message: (NSString *) myMessage {
    [text setStringValue: myMessage]; 
    NSLog(@"Message Was Called");
    // This returns <NSTextField: 0x1001355b0> when called 
    // using self, but null when called the other way.
    NSLog(@"%@", text);
}

@end

I've searched for a while, but still can't find the answer.

I guess it has something to do with the delegate, but I'm not sure.

Thanks in advance.


Are you sure message is called when you call it from anotherFuntion? If anotherFuntion is a method of another class, calling [self message:] won't work as you expected to...


I know this is an old post, but I have been fiddling with the same issue today. You have to return string value in textfield:

[textField stringValue];


The code

TestMessage * messageTest = [TestMessage new];

is unusual, specifically new. I'm going to assume that new is just a class method does normal alloc/init equivalent to

 TestMessage * messageTest = [[TestMessage alloc] init];

The main problem is that IBOutlet NSTextField *text will be initialized only if the class TestMessage is loaded with a Nib file. It would have to be named as the class of an object in Interface Builder, like so

Set value of NSTextField

and you would have to implement initWithCoder and encodeWithCoder something like this in order to extract your field value from the IB encoding:

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        self.text = [coder decodeObjectForKey:@"text"];
    }
    return self;
}


-(void)encodeWithCoder:(NSCoder *)coder
{
    [super encodeWithCoder:coder];
    [coder encodeObject:self.text forKey:@"text"];
}

Fundamentally, IBOutlet fields do not get wired up wherever you create an instance of that class. If they did, how would you express that field A should be wired to UI object A and field B should be wired to UI object B? The connection is established only in the context of loading a class from a Nib file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜