使用GCD編程記住一件事 就可以一招鮮吃遍天了. 刷新界面的代碼 放在這個(gè)block中執(zhí)行dispatch_async(dispatch_get_main_queue(),^{
});
對(duì)于那些要執(zhí)行起來耗時(shí)間的任務(wù)應(yīng)該放到其他的執(zhí)行線程中 不要取阻塞主線程的執(zhí)行
dispatch_async(dispatch_get_global_queue(0,0),^{
});
封裝工具類代碼:
import<UIKit/UIKit.h>
import@interface HJTUtility : NSObject
//產(chǎn)生一個(gè)速度的隨機(jī)數(shù)
+(int) randomIntBetweenMin:(int) min Max:(int) max;
//生成一個(gè)隨機(jī)的顏色
+(UIColor *)randomColor;
//生成一個(gè)隨機(jī)顏色
+(UIColor *)randomColorWithAlpha:(CGFloat) alpha;
@end
import "HJTUtility.h"
@implementation HJTUtility
+(int)randomIntBetweenMin:(int)min Max:(int)max{
return arc4random() % (max - min + 1) + min;
}
+(UIColor *)randomColorWithAlpha:(CGFloat)alpha{
//利用隨機(jī)數(shù)產(chǎn)生隨機(jī)顏色
double red = [self randomIntBetweenMin:0 Max:255]/255.0;
double green = [self randomIntBetweenMin:0 Max:255]/255.0;
double blue = [self randomIntBetweenMin:0 Max:255]/255.0;
//alpha 是透明度
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
+(UIColor *)randomColor{
return [self randomColorWithAlpha:1];
}
@end
建立一個(gè)汽車模型 遵循KVC:
import<UIKit/UIKit.h>
//個(gè)人建議使用這個(gè)定義字面常量 而不是使用#define 因?yàn)槲胰菀着e(cuò) 呵呵
static const int CAR_WIDTH = 30;
static const int CAR_HEITH = 40;
@interface HJTCar : NSObject
//汽車左上角橫坐標(biāo)
@property (nonatomic,assign) NSUInteger x;
//汽車左上角縱坐標(biāo)
@property (nonatomic,assign) NSUInteger y;
//汽車速度
@property (nonatomic,assign) NSUInteger speed;
//和汽車關(guān)聯(lián)的視圖
@property (nonatomic,strong) UIView *view;
//初始化汽車左上角的橫縱坐標(biāo)
-(instancetype) initWithX:(int) x Y:(int)y;
//汽車行駛
-(void) carRun;
//將汽車視圖呈現(xiàn)在父視圖上的方法
-(void) draw:(UIView *)parentView;
@end
import "HJTCar.h"
import "HJTUtility.h"
@implementation HJTCar
-(instancetype)initWithX:(int)x Y:(int)y{
if (self = [super init]) {
_x = x;
_y = y;
_speed = [HJTUtility randomIntBetweenMin:5 Max:9];
_view = [[UIView alloc]initWithFrame:CGRectMake(_x, _y, CAR_WIDTH, CAR_HEITH)];
_view.backgroundColor = [HJTUtility randomColor];
}
return self;
}
-(void)carRun{
while (_y + CAR_HEITH < 650) {
_y += _speed;
CGRect rect = _view.frame;
rect.origin.y = _y;
//蘋果官方建議:刷新視圖的工作 要回到 主線程完成
dispatch_async(dispatch_get_main_queue(), ^{
_view.frame = rect;
});
//休眠50ms --可以產(chǎn)生20幀(流暢的動(dòng)畫效果)
//區(qū)別:sleep()--單位是秒 usleep()--單位是毫秒
usleep(50000);
}
}
-(void)draw:(UIView *)parentView{
[parentView addSubview:_view];
}
@end
下面是UIViewController中的實(shí)現(xiàn)
import<UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
import "ViewController.h"
import "HJTCar.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
for (int i = 0; i < 5; i++) {
HJTCar *car = [[HJTCar alloc]initWithX:20 + 80 * i Y:10];
[car draw:self.view];
// 把程序中會(huì)出現(xiàn)卡頓的地方 放到一個(gè)并發(fā)隊(duì)列中執(zhí)行 避免程序出現(xiàn)卡頓 假死
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[car carRun];
});
}
}
@end