好的。我对 block 不是很清楚,但我经常使用它们;特别是在执行 ASIHTTPRequest 时。我想将一个对象传递到 block 中,并让请求在完成时为对象分配一个值,但我不知道如何使对象在 block 内“可用”。
这是我的方法...
- (void)fetchImageAsynchronously:(NSURL *)theURL intoImageObject:(UIImage *)anImageObject
{
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theURL];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCompletionBlock:^{
NSData *responseData = [request responseData];
anImageObject = [UIImage imageWithData:responseData];
}];
[request setFailedBlock:^{
// NSError *error = [request error];
}];
[request startAsynchronous];
}
因此,当请求完成时,我希望 anImageObject 的值是获取的图像。但是 block 内没有 ImageObject。
有人愿意帮忙吗?
最佳答案
一个 ImageObject 必须通过引用传递。也就是UIImage**,调用方法的时候传入一个ImageObject的地址。
这不是一个很好的设计,因为您还必须管理 anImageObject 的生命周期,并且还可能发布某种它已准备就绪的通知。也就是说,如果在下载图像数据所需的时间内释放了 ImageObject,则此代码将中断。而且您不会知道 ImageObject 是否使用数据进行了初始化。
- (void)fetchImageAsynchronously:(NSURL *)theURL intoImageObject:(UIImage **)anImageObject
{
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theURL];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCompletionBlock:^{
NSData *responseData = [request responseData];
*anImageObject = [UIImage imageWithData:responseData];
}];
[request setFailedBlock:^{
// NSError *error = [request error];
}];
[request startAsynchronous];
}
关于ios - 将对象传递到 ASIHTTPRequest block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9073954/