ios - AFNetworking用于图像下载,UI无响应

标签 ios multithreading core-data thread-safety afnetworking

我正在使用AFNetworking从URL中提取图像,调整大小,存储到磁盘并在Core Data中记录路径,然后加载到表格 View 并存储。当代码执行时,它冻结了我的UI。我不确定是下载还是操作引起了我的麻烦。

我正在使用的代码如下

- (void)getPhoto:(NSInteger)type forManagedObject:(MyManagedObject*)object {

    // download the photo
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:object.photoUrl]];
    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request success:^(UIImage *image) {


        // MyManagedObject has a custom setters (setPhoto:,setThumb:) that save the
        // images to disk and store the file path in the database 
        object.photo = image;
        object.thumb = [image imageByScalingAndCroppingForSize:CGSizeMake(PhotoBlockCellButtonWidth, PhotoBlockCellButtonHeight)];

        NSError *nerror;
        if (![[DataStore sharedDataStore].managedObjectContext save:&nerror]) {
            NSLog(@"Whoops, couldn't save: %@", [nerror localizedDescription]);
            return;
        }

        // notify the table view to reload the table
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadTableView" object:nil];

    }];
    [operation start];
}

这是与我的托管对象中的设置者相关的示例代码
- (NSString*)uniquePath{

    // prepare the directory string
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // acquire a list of all files within the directory and loop creating a unique file name
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *existingFiles = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSString *uniquePath;
    do {
        CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
        CFStringRef newUniqueIdString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);

        uniquePath = [[documentsDirectory stringByAppendingPathComponent:(__bridge NSString *)newUniqueIdString] stringByAppendingPathExtension:@"png"];

        CFRelease(newUniqueId);
        CFRelease(newUniqueIdString);
    } while ([existingFiles containsObject:uniquePath]);

    return uniquePath;
}

- (NSString*)saveImage:(UIImage*)image{
    NSString *path = [self uniquePath];
    NSData *data = UIImagePNGRepresentation(image);
    [data writeToFile:path atomically:YES];
    return [NSString stringWithFormat:@"file://%@",path];
}

- (void) setPhoto:(UIImage *)image {
    self.photoUrl = [self saveImage:image];
}

我想将其推送到后台线程,但是我不确定在线程安全方面,AFNetworking,Core Data和Messaging的含义是什么。任何想法?

最佳答案

AFAIK,您执行请求的方式不正确:

[operation start];

您应该改为将操作添加到NSOperationQueue:
    NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue addOperation:operation];

(您应该正确地对队列进行内存管理)。

这样,您的请求将以异步方式执行,不会阻塞UI,并且您将不需要处理多线程。

关于ios - AFNetworking用于图像下载,UI无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10078092/

相关文章:

ios - 如何在 iOS 中播放 .m3u8 或 .ts 文件?

ios - NSRangeException - 无法删除观察者

c# - 基于网络的任务的多线程/并发策略

java线程和jtabbedpane

c# - ConcurrentDictionary 和原子操作——有时需要 Lock 吗?

ios - 如何动态更改本地化 SwiftUI

swift - 到许多逆过程

ios - NSFetchedResultsController 的复杂获取请求

ios - SwiftUI:从单元格 View 中删除托管对象会使应用程序崩溃[非可选属性]?

ios - 生成二维码