首先,請原諒我的英語不好,但我是法語,我會盡我所能來理解。創建一個外部web服務,並在viewdidload中調用它
所以,我的編碼與此結構的簡單應用: - 的viewController類(成交與UI) - 產品類(定義對象產品) - ws_product類(包含一些功能,這讓JSON DATAS)
我想要做的是返回產品數組,我得到後我在我的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類返回它,我該怎麼辦?
什麼是你的問題? – KIDdAe
我想知道如何返回數組「結果」 – neobagram
當您調用此函數時,結果將爲空,因爲實際的webrequest和數據解析將異步完成。因此,您可能希望查看委託,協議或考慮使用塊來處理異步Web請求和處理。 – HRM