原子核非原子屬性的選擇
OC在定義屬性時有nonatomic和atomic兩種
atomic:原子屬性,為setter方法加鎖(默認就是atomic)
nonatomic:非原子屬性,不會為setter方法加鎖
nonatomic和atomic對比
atomic:線程安全,需要消耗大量的資源
nonatomic:非線性安全,適合內存小的移動設備
iOS開發(fā)建議
所有屬性都聲明為nonatomic
盡量避免多線程搶奪同一塊資源
盡量將加鎖/資源搶奪的業(yè)務邏輯交給服務器端處理,減小移動客戶端的壓力
線程間通信
什么叫做線程間通信
在1個進程中,線程往往不是孤立存在的,多個線程之間需要進行通信
1個線程傳遞數(shù)據(jù)給另1個線程
在1個線程中執(zhí)行完特定任務后,轉到另外一個線程中繼續(xù)執(zhí)行
線程間通信實例-圖片線程

聲明屬性
在storyBoard拖UIImageView并關聯(lián)屬性
@property (weak,nonatomic) IBOulet UIImageView *imageView;
//在主線程下載圖片計算下載圖片消耗時間
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//圖片的網(wǎng)絡路徑
NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
//下載開始時間
NSDate *begin = [NSDate date];
//根據(jù)圖片的網(wǎng)絡路徑去下載圖片數(shù)據(jù)(比較耗時間)
NSData *data = [NSData dataWithContentsOfURL:url];
//下載結束時間
NSDate? *end = [NSDate date];
//記錄下載所花的時間
NSLog(@"%f",[end timeIntervalSinceDate:begin]);?
//顯示圖片
self.imageView.image = [UIImage imageWithData:data];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//[self download2];
//創(chuàng)建子線程,去子線程加載圖片
[self performSelectorInBackground:@selector(download3) withObject:nil];
}
/在主線程下載圖片計算下載圖片消耗時間
- (void)download2{
//圖片的網(wǎng)絡路徑
NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
//下載開始時間
CFTimeInterval? begin = CFAbsoluteTimeGetCurrent();
//根據(jù)圖片的網(wǎng)絡路徑去下載圖片數(shù)據(jù)(比較耗
時間)
NSData *data = [NSData dataWithContentsOfURL:url];
//下載結束時刻的時間
CFTimeInterval??end = CFAbsoluteTimeGetCurrent();
NSLog(@"%f",[end timeIntervalSinceDate:begin]);
//顯示圖片
self.imageView.image = [UIImage imageWithData:data];
}
- (void)download3{
//圖片的網(wǎng)絡路徑
NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
//根據(jù)圖片的網(wǎng)絡路徑去下載圖片數(shù)據(jù)(比較耗
時間)
NSData *data = [NSData dataWithContentsOfURL:url];
//顯示圖片
UIImage *image?= [UIImage imageWithData:data];
//回到主線程
//方法
//[self performSelectorOnMainThread:?@selector(showImage:) withObject:image waitUntilDone: YES];
//方法2
//[self.imageView? performSelectorOnMainThread:@selector(setImage:) withObject : image withUntilDone:NO];
//方法3
[self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject: image waithUntilDone:NO];
}
//- (void) showImage:(UIImage *)image{
//self.imageView.image = image;
//}
//另外一種線程之間的通信
//NSPort;
//NSMessagePort;
//NSMachPort;
