Can the state of an NSButton be changed from any method?

Discussion in 'Mac Programming' started by HungrySeacow, Mar 4, 2006.

  1. macrumors regular

    Joined:
    Jan 11, 2006
    Location:
    West Palm Beach
    #1
    The method that my NSButton calls, calls another method, via an NSTimer. Since any code in the method that calls the NSTimer will execute before the NSTimer is finished, I would like the same function that invalidates the NSTimer which is in the method that is called by the NSTimer to be able to set the NSButton state back to 0. I know that sounds terribly confusing so here is the code:
    Code:
    - (IBAction)start:(id)sender
    {
    	if ([sender state] == 1) {
    		stringData = [[NSString alloc] initWithString:@"Text to be scrolling :)"];
    		mutableString = [[NSMutableString alloc] initWithString:@""];
    		x = 0;
    		timer = [NSTimer scheduledTimerWithTimeInterval:0.2
    												 target:self
    											   selector:@selector(changeText)
    											   userInfo:nil
    												repeats:YES];
    		
    	} else {
    		[timer invalidate];
    	}
    
    }
    
    - (void)changeText
    {
        theChar = [stringData characterAtIndex:x];
    	intermediateMutableString = [NSMutableString stringWithCharacters:&theChar length:1];
    	[mutableString appendString:intermediateMutableString];
    	[textField1 setStringValue: mutableString];
    	x++;
    	if ([mutableString length] == [stringData length]) {
    		[timer invalidate];
    	}
    }
    
    As you can see, once the sequence is finished, the NSButton will still be at the state that will call the [timer invalidate]; when pressed, crashing the program. Is there a way to get the -changeText method to change the state of the button when it invalidates the timer?
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    I'll answer the title as I can't make much out of the body text! Yes any method can change the state of an NSButton as long as:

    1) The method is running in the main thread (AppKit is not thread safe)

    2) The button is in scope. Normally as long as the method is part of a class you have connected to the button via an IBOutlet you'll be fine. Otherwise you can pass a variable pointing to the button around...
     
  3. thread starter macrumors regular

    Joined:
    Jan 11, 2006
    Location:
    West Palm Beach
    #3
    Thanks! It had not thought of just adding an IBOutlet to the button itself. Thanks again!
     

Share This Page