Objective c 数据加载到模型对象后,如何打开视图控制器?
如何检查辅助线程中的Objective c 数据加载到模型对象后,如何打开视图控制器?,objective-c,json,model,nsdata,Objective C,Json,Model,Nsdata,如何检查辅助线程中的NSData dataWithContentsOfURL解析是否已完成?当每个图像完成后,我想打开我的视图控制器。以前没有。现在我可以直接打开我的视图控制器,有时如果我要快速,我的表视图没有图像,因为它们还没有完成。有什么想法吗 以下代码发生在AppDelegate中的didFinishLaunchingWithOptions中。Im使用SBJSON框架进行解析 (我在此项目中使用情节提要,因此没有打开第一视图控制器的代码) 代码: 另外,如果这种解析方法不好,请告诉我 首先
NSData dataWithContentsOfURL
解析是否已完成?当每个图像完成后,我想打开我的视图控制器。以前没有。现在我可以直接打开我的视图控制器,有时如果我要快速,我的表视图没有图像,因为它们还没有完成。有什么想法吗
以下代码发生在AppDelegate中的didFinishLaunchingWithOptions
中。Im使用SBJSON框架进行解析
(我在此项目中使用情节提要,因此没有打开第一视图控制器的代码)
代码:
另外,如果这种解析方法不好,请告诉我 首先,您不应该使用这种方式从远程主机下载任何内容。 有很多图书馆,比如 它围绕CFNetwork或NSURLConnection来处理重定向、错误处理等事情。 因此,您肯定应该选择其中一种(或者基于NSURLConnection实现您自己的) 作为对您问题的直接回答: 您应该使用某种标识符来计算下载的图像(即循环迭代计数器),并通过+[UINotificationCenter defaultCenter]将其作为某个自定义通知的参数传递 示例(假设您正在通过+[NSData dataWithContentsOfURL:]阻止当前线程): 您还可以使用回调技术来管理下载状态的处理:
void (^callback)(id result, int identifier) = ^(id result, int identifier) {
if (identifier == 10) {
// do some work afterwards
}
};
for (int i = 0; i < 10; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, kNilOptions), ^{
// some downloading stuff which blocks thread
id data = nil;
callback(data, i);
});
}
void(^callback)(id-result,int-identifier)=^(id-result,int-identifier){
如果(标识符==10){
//之后做些工作
}
};
对于(int i=0;i<10;i++){
调度异步(调度获取全局队列(调度队列优先级后台、编织)^{
//一些正在下载的东西会阻塞线程
id数据=零;
回调(数据,i);
});
}
for (int i = 0; i < 10; i++) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"someCustomNotificationClassName" object:nil userInfo:@{ @"counter" : @(i) }];
}
- (id)init {
self = [super init];
if (self) {
// subscribing for notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDataDownload:) name:@"someCustomNotificationClassName" object:nil];
}
return self;
}
- (void)dealloc {
// unsubscribing from notification on -dealloc
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - downloading delegation
- (void)handleDataDownload:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
int counter = [userInfo[@"counter"] intValue];
if (counter == 10) {
// do some work afterwards
// assuming that last item was downloaded
}
}
void (^callback)(id result, int identifier) = ^(id result, int identifier) {
if (identifier == 10) {
// do some work afterwards
}
};
for (int i = 0; i < 10; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, kNilOptions), ^{
// some downloading stuff which blocks thread
id data = nil;
callback(data, i);
});
}