我正在使用Objective C和Cocoa为Mac OS X编写一个应用程序,它从外部源加载GIF并在屏幕上显示它们。用户搜索一个术语,下载GIF并将其放入NSImageViews,然后这些视图以滚动视图显示。
早些时候,GIF按预期动画。然后我尝试使用NSThread来加载GIF并添加到与主线程分开的滚动视图。这是在线程中调用的方法:
- (void)threading:(id)obj
{
NSURL *url = [NSURL URLWithString: @"URL HERE"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSURLResponse *response;
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error] options:NSJSONReadingMutableLeaves error:nil];
NSArray *gifs = [data objectForKey:@"data"];
for (int i = 0; i < 1; i++) { // try to load 1 gif
NSString *currentGifURL = @"whatever";
NSImageView *imgView = [[NSImageView alloc] initWithFrame:CGRectMake(10, 1820-100*i, 150, 120)];
// I tried using these 2 lines, still didn't work
//[imgView setAnimates:YES]; [imgView setImageScaling:NSScaleNone];
NSURL *imageURL = [NSURL URLWithString:currentGifURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
NSImage *image = [[NSImage alloc] initWithData:imageData];
imgView.image = image;
[_scrollView.documentView addSubview:imgView];
}
[_progressIndicator stopAnimation:self];
}
我稍后打电话给
[NSThread detachNewThreadSelector:@selector(threading:) toTarget:self withObject:nil];
创建线程。图像显示在屏幕上,但只显示第一帧 - 它们不是动画。直接用线程内部的代码替换线程初始化呈现相同的视图,除了GIF是动画的。有什么关于线程会阻止GIF动画?
谢谢!
答案 0 :(得分:1)
NSImageView
不是线程安全的。使用- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
- (void)threading:(id)obj
{
NSURL *url = [NSURL URLWithString: @"URL HERE"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSURLResponse *response;
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error] options:NSJSONReadingMutableLeaves error:nil];
NSArray *gifs = [data objectForKey:@"data"];
for (int i = 0; i < 1; i++) { // try to load 1 gif
NSString *currentGifURL = @"whatever";
// I tried using these 2 lines, still didn't work
//[imgView setAnimates:YES]; [imgView setImageScaling:NSScaleNone];
NSURL *imageURL = [NSURL URLWithString:currentGifURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
NSImage *image = [[NSImage alloc] initWithData:imageData];
[self performSelectorOnMainThread:@selector(LoadImageView:) withObject:image waitUntilDone:NO];
}
[_progressIndicator stopAnimation:self];
}
-(void)LoadImageView : (NSImage *)image
{
NSImageView *imgView = [[NSImageView alloc] initWithFrame:CGRectMake(10, 1820-100*i, 150, 120)];
imgView.image = image;
[_scrollView.documentView addSubview:imgView];
}