本次記錄是在子線程中進行計算給出隨機值禁谦,并在主線程中隔時創(chuàng)建label進行動畫上浮展示效果。
//時間废封、上浮速度州泊、創(chuàng)建多少都可控。
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// 可以用該語句查看當前線程
NSLog(@"當前線程--%@", [NSThread currentThread]);
// 此處需要寫一個異步任務漂洋,是因為需要開辟一個新的線程去反復執(zhí)行你的代碼塊遥皂,否則會阻塞主線程
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
while (TRUE) {
// 每隔5秒執(zhí)行一次(當前線程阻塞5秒)
[NSThread sleepForTimeInterval:0.2];
// [[UIApplication sharedApplication] cancelAllLocalNotifications];
// 這里寫你要反復處理的代碼力喷,如網(wǎng)絡請求
// NSLog(@"***每5秒輸出一次這段文字***");
int a = arc4random()%5;
UIGraphicsBeginImageContext(CGSizeMake(a, a));//設(shè)置上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctx);
CGContextAddArc(ctx, a/2, a/2, a/2, 0, 2*M_PI, 0);
CGContextSetRGBFillColor (ctx, 2, 2, 0, 1.0);//設(shè)置填充顏色
CGContextFillPath(ctx);
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
UILabel*theLabOne = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-arc4random()%60, self.view.frame.size.height-arc4random()%60-20, a, a)];
theLabOne.backgroundColor = [UIColor greenColor];
[self.view addSubview:theLabOne];
[UIView animateKeyframesWithDuration:(10.0)//動畫持續(xù)時間
delay:(0.01)//動畫延遲執(zhí)行的時間
options:(UIViewAnimationOptionTransitionNone)//動畫的過渡效果
animations:^{
//執(zhí)行的關(guān)鍵幀動畫
//執(zhí)行的動畫
theLabOne.frame = CGRectMake(self.view.frame.size.width/2-arc4random()%60, -10, a, a);
}
completion:^(BOOL finished) {
}];
});
// [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
};
});