Suryavel TR
Suryavel TR

Reputation: 3806

Facing Difficulty With NSThread While Trying To Animate Label

I'm very new to IOS programming and i have doubt with NSThread. My problem is, i have a UILabel in my view and i want to hide and make it visible Successively after every 5 second. For this purpose i've used NSThread as below.

[NSThread detachNewThreadSelector:@selector(animate) toTarget:self withObject:nil];

    -(void) animate
    {
        while(animateLabel){
               [NSThread sleepForTimeInterval:5];
                if(label.hidden){
                    NSLog(@"Label is hidden");
                    [label setHidden:NO];
                }else
                 { 
                    NSLog(@"Label is vissible");
                   [label setHidden:YES];
                   }


  }
}

Now i'm getting "Label is hidden" and "Label is vissible" Successively in log after every 5 seconds. But my label is not getting hide.

I did with NSTimer and it's working.

But, what is the problem with above code ?. If no problem with this code, Why NSThread couldn't do ?

Upvotes: 0

Views: 205

Answers (3)

nswamy
nswamy

Reputation: 1051

You need to perform this on a main thread instead.

Try this -

[NSThread performSelectorOnMainThread:@selector(animate) toTarget:self withObject:nil];

since you have while loop

remove sleep and add runloop

[[NSRunLoop currentRunLoop] runUntilDate:(NSDate*)]

Upvotes: 1

J_S
J_S

Reputation: 561

My Bad, didn't read that you purposely intended to do it with NSThread, here's how to do it with NSTimer anyway:

If you create NSTimer from the main thread you don't even need to deal with threading safety-issues.

declare an NSTimer in the Header file so you can reach it in case you want to cancel it or something (I'm also assuming your label is named 'mainLabel' and is declared properly):

NSTimer *labelVisibilityTimer;
@property (nonatomic,retain) NSTimer *labelVisibilityTimer;

in your implementation file, properly synthesize the Timer and initialize it with the method that will trigger the visibility change.

@synthesize labelVisibilityTimer;

- (void)viewDidLoad{
    self.labelVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(toggleVisibilityOfLabel) userInfo:nil repeats:YES];
}

-(void)toggleVisibilityOfLabel{
    mainLabel.hidden = !mainLabel.hidden;
}


- (void)viewDidUnload{
    [super viewDidUnload];
    self.labelVisibilityTimer = nil;
}

- (void) dealloc{
    [super dealloc];
    [labelVisibilityTimer release];
}

Upvotes: 0

iOSPawan
iOSPawan

Reputation: 2894

UI can be changed only by main thread. instead of creating new thread you can use selector try this -

[self performSelectorOnMainThread:@selector(animate) withObject:nil afterDelay:5.0 ];

Upvotes: 0

Related Questions