Skip to content

Instantly share code, notes, and snippets.

@hamadmj
Last active November 16, 2015 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hamadmj/2b081aa570bc150a966f to your computer and use it in GitHub Desktop.
Save hamadmj/2b081aa570bc150a966f to your computer and use it in GitHub Desktop.
Challenge 1
@interface XYZWaitController : UIViewController
@property (strong, nonatomic) UILabel *alert;
@end
@implementation XYZWaitController
- (void)viewDidLoad
{
CGRect frame = CGRectMake(20, 200, 200, 20);
self.alert = [[UILabel alloc] initWithFrame:frame];
self.alert.text = @"Please wait 10 seconds...";
self.alert.textColor = [UIColor whiteColor];
[self.view addSubview:self.alert];
NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];
[waitQueue addOperationWithBlock:^{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];
self.alert.text = @"Thanks!";
}];
}
@end
@implementation XYZAppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = [[XYZWaitController alloc] init];
[self.window makeKeyAndVisible];
return YES;
}
@yahya-alshaar
Copy link

// The problem here:
NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];
[waitQueue addOperationWithBlock:^{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];
self.alert.text = @"Thanks!";
}];

// You should access the UI throw main thread like this to grantee the block will execute on the main thread:
NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];
[waitQueue addOperationWithBlock:^{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];
[[NSOperationQueu mainQueue] addOperationWithBlock:^{
self.alert.text = @"Thanks!";
}];
}];

@amrabdelaal
Copy link

The problem is that ui elements must changed in main queue then you can write:

NSOperationQueue *waitQueue = [NSOperationQueue mainQueue];
[waitQueue addOperationWithBlock:^{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];
self.alert.text = @"Thanks!";
}];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment