gpt4 book ai didi

ios - 创建一个外部网络服务并在 viewdidload 中调用它

转载 作者:行者123 更新时间:2023-11-28 22:23:19 25 4
gpt4 key购买 nike

首先,请原谅我的英语不好,但我是法国人,我会尽力让人们理解。

所以,我正在用这种结构编写一个简单的应用程序:- viewController 类(处理 UI)- 产品类(定义对象产品)- ws_product 类(包含一些获取 json 数据的函数)

我想要做的是返回产品数组,这是我在我的 viewController 中解析 ws_product 中的 json 之后得到的。多亏了这个,我可以填充我的 tableView,我的应用程序将不再是空的!

我的实际 ws_product 是:

#import "WS_Produit.h"
#import "Produit.h"
#import "ViewController.h"

@implementation WS_Produit

- (NSMutableArray *)getProduitsJSON
{
__block NSMutableArray *result;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^() {

NSLog(@"on passe en async");

NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"the url to load"]];
NSDictionary *produits = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];


if( error )
{
NSLog(@"%@", [error localizedDescription]);
}
else {
dispatch_sync(dispatch_get_main_queue(), ^(){

NSLog(@"retour en sync");
result = [[NSMutableArray alloc] init];
Produit *tmp;

NSArray *produit = produits[@"produits"];
for ( NSDictionary *property in produit )
{
tmp = [Produit new];
tmp.ref = property[@"ref"];
tmp.name = property[@"name"];
tmp.description = property[@"description"];
tmp.price = property[@"price"];
tmp.imgURL = property[@"imgURL"];

[result addObject:tmp];
NSLog(@"%@", result);
}
});
}
});
NSLog(@"sortie du block");
NSLog(@"%@", result);
return result;
}

@end

我的问题是当我离开 dispatch_queue 时我的结果数组是空的所以在我的 viewController 类中返回它是没有用的,我该怎么办?

最佳答案

因为您使用的是 dispatch_async,所以您的结果数组在填充之前将返回为空。

积木正是您所需要的。它们可以用作异步方法的回调。

在您的 viewController 中,您应该将 block 传递给您的方法

[myObject getProduitsJSON:
success:^(NSArray *results){
// Use your results here
// Reload table for example.
}
failure:^(NSError *error){
// Use your error message (show it for example)
}];

所以你的方法应该是这样的:

-(void)getProduitsJson:(void(^)(NSArray* results))success failure:(void(^)(NSError* error))failure {
{
NSMutableArray *result = [[NSMutableArray alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^() {
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"the url to load"]];
NSDictionary *produits = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

if(error) {
failure(error);
}else{
// Fill your array
success(result);
}
}
}

关于ios - 创建一个外部网络服务并在 viewdidload 中调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19702142/

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