gpt4 book ai didi

ios - 在 for 循环中处理 UI 更新 - iOS

转载 作者:行者123 更新时间:2023-11-28 18:58:45 25 4
gpt4 key购买 nike

我正在使用 NSNotificationcentre 从 for 循环更新 UI。在执行退出循环之前,UI 不会更新。有办法处理这种情况吗?下面是我的代码:

- (void)uploadContent{
NSURLResponse *res = nil;
NSError *err = nil;



for (int i = 0; i < self.requestArray.count; i++) {

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[[NSNotificationCenter defaultCenter] postNotificationName:kUpdatePreviewImageView object:nil userInfo:@{@"image": [self.imageArray objectAtIndex:i],@"count":[NSNumber numberWithInt:i],@"progress":[NSNumber numberWithFloat:0.5f]}];
}];
ImageUploadRequest *request = [self.requestArray objectAtIndex:i];


NSData *data = [NSURLConnection sendSynchronousRequest:request.urlRequest returningResponse:&res error:&err];
if (err) {

NSLog(@"error:%@", err.localizedDescription);
}
NSError *jsonError;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&jsonError];

NSLog(@"current thread %@",[NSThread currentThread]);

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[[NSNotificationCenter defaultCenter] postNotificationName:kUpdatePreviewImageView object:nil userInfo:@{@"image":[self.imageArray objectAtIndex:i],@"count":[NSNumber numberWithInt:i],@"progress":[NSNumber numberWithFloat:1.0f]}];
}];
}


[[NSNotificationCenter defaultCenter] postNotificationName:kImageUploaded object:nil];


}

在我的 viewcontroller.m 文件中,我在 viewdidLoad() 下声明了观察者

[[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(updatePreviewView:) name:kUpdatePreviewImageView object:nil];

updatepreview: 类定义如下:

-(void)updatePreviewView:(NSNotification *)notify{


NSDictionary *previewImageDetails = [notify userInfo];

self.previewImageView.image = previewImageDetails[@"image"];



hud.labelText = [NSString stringWithFormat:@"Uploading media %@ of %lu",previewImageDetails[@"count"],(long unsigned)self.mediaDetail.count];


hud.progress = [previewImageDetails[@"progress"] floatValue];

}

最佳答案

由于 for 循环正在运行主线程,因此该线程会被阻塞,直到 for 查找完成。由于主要威胁也是 UI 线程,您的 UI 更新在循环完成之前不会完成。

您应该在后台线程上运行循环,如果它们在主线程上异步运行,UI 会发生变化。

并在您的 updatePreviewView: 中确保代码将在主线程上运行。

关于ios - 在 for 循环中处理 UI 更新 - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28670879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com