Obj-C & # 8594; Increase in number (and showing steps on Cocoa label)

I am new to Objective-C, so maybe this is a simple solution.

I want the number to increase, but each iteration should be displayed on the label. (for example, it shows 1, 2, 3, 4, 5 ... is displayed separately for the amount of time).

I tried:

#import "testNums.h"

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

and all he did was wait for 9 seconds (obviously frozen) and then display 9 in the text box.

+3
source share
2 answers

To allow the execution cycle to run between messages, use NSTimeror delay the execution. Here's the last one:

- (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 is one timer based solution. It may be easier for you to follow. You can set the value of the text field 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 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 value immediately to 0
    self.currentNumber = 0;
}

- (void) updateTextField:(NSTimer *)timer {
    self.currentNumber = ++currentNumber;
}

@end

, , :

  • . ( , , .)
  • , IB. - TestNums.
+6

, , . , . NSTimer - , , .

, ?

+4

Source: https://habr.com/ru/post/1698720/


All Articles