Obj-C→递增一个数字(并在Cocoa标签上显示步骤) [英] Obj-C -> Incrementing a number (and showing steps on a Cocoa label)
问题描述
我是Objective-C的新手,所以可能有一个简单的解决方案。
I'm new with Objective-C, so there probably is a simple solution to this.
我想要一个数字递增,但每次迭代显示在标签上。 (例如,它显示1,2,3,4,5 ...显示分开的时间量)。
I want a number to increment, but each iteration to be show on a label. (for example, it shows 1, 2, 3, 4, 5... displayed apart by an amount of time).
我试过:
#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。
and all it did was wait for 9 seconds (apparently frozen) and then displayed 9 in the text box.
推荐答案
消息,请使用 NSTimer
或延迟执行。这是后者:
To allow the run loop to run between messages, use an NSTimer
or delayed perform. Here's the latter:
- (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];
}
这里有一个基于定时器的解决方案。你可能会发现它更容易遵循。您可以从文本字段中设置文本字段的值:
Here's one timer-based solution. You may find it easier to follow. You could set the text field's value from the text field:
@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
作为键绑定)。
Here's an even better (cleaner) timer-based solution, using a property. You'll need to bind the text field to the property in Interface Builder (select the field, press ⌘4, choose your object, and enter currentNumber
as the key to bind to).
@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
基于属性的解决方案至少有两个优点:
The property-based solution has at least two advantages:
- 你的对象不需要知道文本字段。 (它是一个模型对象,与文本字段的视图对象分开。)
- 要添加更多文本字段,只需在IB中创建和绑定它们。您不必向TestNums类中添加任何代码。
这篇关于Obj-C→递增一个数字(并在Cocoa标签上显示步骤)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!