在文本字段中设置文本在Obj-C中不起作用

时间:2013-10-07 23:54:24

标签: objective-c text properties set

我想在另一个类的文本字段中设置一个文本,并从另一个类中获取它。这是我想要的东西,但它不起作用。你能帮我么。谢谢!

aaa.h

#import <Cocoa/Cocoa.h>

@interface aaa : NSImageView {
    IBOutlet NSTextField *message;
}
@property (nonatomic, retain) IBOutlet NSTextField *message;
@end

aaa.m

#import "aaa.h"
#import "bbb.h"

@implementation aaa
@synthesize message;

- (void)awakeFromNib {
    // [message setStringValue:@"ok, this works!"]; //but i don't want it from here
    [self hello];
}
@end

bbb.h

#import <Foundation/Foundation.h>

@interface NSObject (bbb)
- (void)hello;
@end

bbb.m

#import "bbb.h"
#import "aaa.h"

@implementation NSObject (bbb)
- (void)hello {
    aaa *obj = [[[aaa alloc] init] autorelease];
    [obj.message setStringValue:@"This doesn't work :("]; // set text here, dont work.
    NSLog(@"TEST: %@", [obj.message stringValue]);
}
@end

1 个答案:

答案 0 :(得分:1)

您正在使用类别,因此首先它用于扩展现有类的功能。因此您无法在类别中设置文本字段值。但是,您可以在提取值后添加一些功能。所以你必须先在类别中传递值。请尝试以下方式:

- (void)awakeFromNib {
    NSString *resultString=[self hello:@"This doesn't work :("];
[message setStringValue:resultString];
}
@end


@interface NSObject (bbb)
- (NSString*)hello:(NSString*)yourString;
@end

@implementation NSObject (bbb)
- (NSString*)hello:(NSString*)yourString {
    return yourString;
}
@end