objective-c – Obj-C – >递增一个数字(并在Cocoa标签上显示步骤)

objective-c – Obj-C – >递增一个数字(并在Cocoa标签上显示步骤),第1张

概述我是Objective-C的新手,所以可能有一个简单的解决方案. 我想要一个数字递增,但每次迭代都要显示标签上. (例如,它显示1,2,3,4,5 ……分开显示一段时间). 我试过了: #import "testNums.h"@implementation testNums- (IBAction)start:(id)sender { int i; for(i = 0; i 我是Objective-C的新手,所以可能有一个简单的解决方案.

我想要一个数字递增,但每次迭代都要显示在标签上. (例如,它显示1,2,3,4,5 ……分开显示一段时间).

我试过了:

#import "testNums.h"@implementation testNums- (IBAction)start:(ID)sender {    int i;    for(i = 0; i < 10; ++i)    {        [outputNum setIntValue:i];        sleep(1);    }}@end

它所做的只是等待9秒(显然是冻结的),然后在文本框中显示9.

解决方法 要允许运行循环在消息之间运行,请使用NSTimer或延迟执行.这是后者:

- (IBAction) start:(ID)sender {    [self performSelector:@selector(updateTextFIElDWithNumber:) withObject:[NSNumber numberWithInt:0] afterDelay:1.0];}- (voID) updateTextFIElDWithNumber:(NSNumber *)num {    int i = [num intValue];    [outputFIEld setIntValue:i];    if (i < 10)        [self performSelector:@selector(updateTextFIElDWithNumber:) withObject:[NSNumber numberWithInt:++i] afterDelay:1.0];}

这是一个基于计时器的解决方案.您可能会发现它更容易理解.您可以从文本字段设置文本字段的值:

@interface TestNums: NSObject{    IBOutlet NSTextFIEld *outputFIEld;    NSTimer *timer;    int currentNumber;}@end@implementation TestNums- (IBAction) start:(ID)sender {    timer = [[NSTimer scheduledTimerWithTimeInterval:1.0        target:self        selector:@selector(updateTextFIEld:)        userInfo:nil        repeats:YES] retain];    //Set the fIEld's value immediately to 0    currentNumber = 0;    [outputFIEld setIntValue:currentNumber];}- (voID) updateTextFIEld:(NSTimer *)timer {    [outputFIEld setIntValue:++currentNumber];}@end

这是一个使用属性的更好(更清洁)的基于计时器的解决方案.您需要将文本字段绑定到Interface Builder中的属性(选择字段,按⌘4,选择您的对象,然后输入currentNumber作为要绑定的键).

@interface TestNums: NSObject{    //NOTE: No outlet this time.    NSTimer *timer;    int currentNumber;}@property int currentNumber;@end@implementation TestNums@synthesize currentNumber;- (IBAction) start:(ID)sender {    timer = [[NSTimer scheduledTimerWithTimeInterval:1.0        target:self        selector:@selector(updateTextFIEld:)        userInfo:nil        repeats:YES] retain];    //Set the fIEld's value immediately to 0    self.currentNumber = 0;}- (voID) updateTextFIEld:(NSTimer *)timer {    self.currentNumber = ++currentNumber;}@end

基于属性的解决方案至少有两个优点:

>您的对象无需了解文本字段. (它是一个模型对象,与作为文本字段的视图对象分开.)>要添加更多文本字段,只需在IB中创建并绑定它们即可.您不必向TestNums类添加任何代码.

总结

以上是内存溢出为你收集整理的objective-c – Obj-C – >递增一个数字(并在Cocoa标签上显示步骤)全部内容,希望文章能够帮你解决objective-c – Obj-C – >递增一个数字(并在Cocoa标签上显示步骤)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1033066.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存