如何正确地将可变字符串发送到 NSTextField ?
所以我已经调试了所有这些代码,看起来没问题。我制作了一个可变字符串,由于某种原因,我无法将其显示在我的标签上。调试器显示
“2010-04-22 22:50:26.126 Fibonacci[24836:10b] *** -[NSTextField setString:]: 无法识别的选择器发送到实例 0x130150”
这有什么问题吗?当我将字符串发送到 NSLog 时,结果很好。
这是我的所有代码,任何帮助将不胜感激。 “elementNum”是一个组合框,“display”是一个标签。 谢谢
#import "Controller.h"
@implementation Controller
- (IBAction)computeNumber:(id)sender {
int x = 1;
int y = 1;
NSMutableString *numbers = [[NSMutableString alloc] init];
[numbers setString:@"1, 1,"];
int num = [[elementNum objectValueOfSelectedItem]intValue];
int count = 1;
while (count<=num) {
int z = y;
y+=x;
x=z;
[numbers appendString:[NSString stringWithFormat:@" %d,", y]];
count++;
}
[display setString:numbers];
NSLog(numbers);
}
@end
`
So I have all this code that I have debugged and it seems to be fine. I made a mutable string and for some reason I can not get it to be displayed on my label. the debugger says
"2010-04-22 22:50:26.126 Fibonacci[24836:10b] *** -[NSTextField setString:]: unrecognized selector sent to instance 0x130150"
What is wrong with this? When I just send the string to NSLog, it comes out fine.
here's all my code, any help would be appreciated. "elementNum" is a comboBox and "display" is a Label.
Thanks
#import "Controller.h"
@implementation Controller
- (IBAction)computeNumber:(id)sender {
int x = 1;
int y = 1;
NSMutableString *numbers = [[NSMutableString alloc] init];
[numbers setString:@"1, 1,"];
int num = [[elementNum objectValueOfSelectedItem]intValue];
int count = 1;
while (count<=num) {
int z = y;
y+=x;
x=z;
[numbers appendString:[NSString stringWithFormat:@" %d,", y]];
count++;
}
[display setString:numbers];
NSLog(numbers);
}
@end
`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看您收到的错误消息:
这告诉您一些事情。具体来说,该
NSTextField
没有-setString:
方法,尝试调用它将会失败。这是您查看
NSTextField
文档的提示。当您这样做时,您将看到没有方法可以设置字符串值。但是,文档还向您展示了NSTextField
继承自NSControl
,后者具有-setStringValue:
方法。因此,您需要调用
-setStringValue:
来设置NSTextField
的值。请注意,目前在您的代码中,您正在泄漏
numbers
字符串对象。您使用-alloc
创建了它,因此您负责释放它。相反,您应该使用
[NSMutableString stringWithString:@"1, 1,"]
创建它,它将返回一个自动释放的对象,并在同一消息中初始化它。Look at the error message you're getting:
This is telling you something. Specifically, that
NSTextField
does not have a-setString:
method and trying to call it will fail.This is your cue to look at the docs for
NSTextField
. When you do so, you will see that there are no methods to set the string value. However, the docs also show you thatNSTextField
inherits fromNSControl
, which has a-setStringValue:
method.So, you need to call
-setStringValue:
to set the value of anNSTextField
.Note that in your code at present, you are leaking the
numbers
string object. You created it using-alloc
, so you are responsible for releasing it.Instead, you should create it using
[NSMutableString stringWithString:@"1, 1,"]
, which will return an autoreleased object, as well as initializing it in the same message.