iOS 多线程(4) 加载图片

创建 UIImageView的类别

UIImageView+webCach.h

#import <UIKit/UIKit.h>

@interface UIImageView (webCach)

-(void)setImageUrl:(NSURL *)url;
@end

#import "UIImageView+webCach.h"

@implementation UIImageView (webCach)
-(void)setImageUrl:(NSURL *)url
{
    
    dispatch_queue_t queue=dispatch_queue_create("loafImage", NULL);
    //异步线程
    dispatch_async(queue, ^{
        NSData *data=[NSData dataWithContentsOfURL:url];
        UIImage *image=[UIImage imageWithData:data];
        
        //让主线程去做
        dispatch_sync(dispatch_get_main_queue(), ^{
            self.image=image;
        });
        
    });
}
@end

#import "MyAppDelegate.h"
#import "UIImageView+webCach.m"
@implementation MyAppDelegate

- (void)dealloc
{
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    count=1;
    //异步加载图片
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(60, 20, 200, 120)];
    imageView.backgroundColor=[UIColor greenColor];
    [imageView setImageUrl:[NSURL URLWithString:@"http://news.imust.cn/UploadFiles/2013/2/2013111815315038005.jpg"]];
    
    UIImageView *imageView2=[[UIImageView alloc]initWithFrame:CGRectMake(60, 180, 200, 120)];
    imageView2.backgroundColor=[UIColor greenColor];
    [imageView2 setImageUrl:[NSURL URLWithString:@"http://news.imust.cn/UploadFiles/2013/2/2013111815315038005.jpg"]];
    
    [self.window addSubview:imageView];
    [self.window  addSubview:imageView2];
    
    UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"按钮" forState:UIControlStateNormal];
    button.frame=CGRectMake(110,320 , 100, 40);
    [button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.window addSubview:button];
    
    return YES;
}

-(void)btnAction:(UIButton *)sender
{
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(count*10, 370, 200, 120)];
    imageView.backgroundColor=[UIColor greenColor];
    [imageView setImageUrl:[NSURL URLWithString:@"http://news.imust.cn/UploadFiles/2013/2/2013111815315038005.jpg"]];
    
    [self.window addSubview:imageView];
    count++;
    //按钮不可用...
    sender.enabled=NO;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值