在實現異步RAC下載圖片的過程當中,須要注意如下幾點:網絡
• 經過 NSURLConnection 對象的 +(RACSignal *)rac_sendAsynchronousRequest:(NSURLRequest*)r 能夠建立網絡異步下載的信號量對象;異步
• 在執行完成異步下載過程後,須要經過 [x deliverOn:[RACScheduler mainThreadScheduler]] 操做將方法返回到主線程進行執行;url
@implementation ViewController { RACCommand *loginCommand; RACSignal *loginSignal; } - (void)awakeFromNib { //建立網絡圖片下載的URL對象 NSURL *url = [NSURL URLWithString:@"http://pica.nipic.com/2007-11-09/2007119124513598_2.jpg"]; //建立網絡圖片請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //實例化命令操做對象 loginCommand = [[RACCommand alloc] initWithSignalBlock:^(id sender) { //經過NSURLConnection的+方法,建立異步返回信號量 return [NSURLConnection rac_sendAsynchronousRequest:request]; }]; //信號量完成後的插座操做 [loginCommand.executionSignals subscribeNext:^(RACSignal *x) { //將下載完成的圖片數據轉換成圖片對象後,在主線程賦值給imageView屬性 [[x deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(RACTuple *tuple) { NSData *imageData = tuple.last; //imageView - UIImageView self.imageView.image = [UIImage imageWithData:imageData]; }]; }]; } - (void)viewDidLoad { [super viewDidLoad]; //指定觸發命令操做 //btn - UIButton self.btn.rac_command = loginCommand; } @end