调度块不会完全运行,同时执行其他代码

时间:2016-04-25 12:41:31

标签: ios objective-c iphone

我遇到了一个大问题。 这是我的代码

#import "NewsAppMenuVC.h"
#import "MenuController.h"
#import "NewsAppTebleCell.h"
#import "NewsAppNewsVC.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD.h"

@interface NewsAppMenuVC ()
{
    MBProgressHUD *HUD;
    News *news;
    NSString *title;
    NSString *abstract;
    NSString *url;
    NSString *byLine;
    NSString *publishedDate;
    NSDictionary *jsonDictionary;
    NSMutableArray *dataArray;
}
@property (nonatomic, strong) MenuController *menuController;
@end


@implementation NewsAppMenuVC

-(void) viewWillAppear:(BOOL)animated
{
self.menuController = [[MenuController alloc]init];
dataArray = [[NSMutableArray alloc]init];

}

- (void)viewDidLoad {
[super viewDidLoad];


self.tableView.delegate = self;
dataArray = [[NSMutableArray alloc]init];

// Do any additional setup after loading the view.
}



-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.menuController newsCount];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NewsAppTebleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newsCell" forIndexPath:indexPath];
news = [self.menuController newsAtIndex:indexPath.row];
cell.newsNameLabel.text = news.newsName;
// Configure the cell...

return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//[HUD showAnimated:YES];
//NSDictionary *resultDictionary = [[NSDictionary alloc]init];
news = [[News alloc]init];
news  = [self.menuController newsAtIndex:indexPath.row];

dispatch_async(dispatch_get_main_queue(), ^{
    [self getRequiredData:news.newsName];
});



UIStoryboard *myStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
NewsAppNewsVC *destVC = [myStoryBoard instantiateViewControllerWithIdentifier:@"NewsAppNewsVC"];
if([dataArray count] == 0)
{
    NSLog(@"Array is empty");
}
else{

    destVC.dataArray = dataArray;
    [self.navigationController pushViewController:destVC animated:YES];
}

}

-(void) getRequiredData:(NSString*)name
{
[HUD showAnimated:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/xml", @"text/json" , nil];
NSLog(@"In getRequiredData method");

[manager GET:@"http://api.nytimes.com/svc/news/v3/content/all/U.S./.json?limit=5&api-key=e024ff0a3fba0e538ed8625bd74cf241%3A7%3A75053716" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
 {
     NSLog(@"Within the API manager");
     jsonDictionary = [[NSDictionary alloc]init];
     jsonDictionary = (NSDictionary *) responseObject;
     //NSDictionary *resultDictionary = [NSDictionary dictionaryWithDictionary:jsonDictionary];
 }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     NSLog(@"Failed %@", error);
 }];

NSLog(@"Filtering results");
NSArray *resultsArray = jsonDictionary[@"results"];
//NSLog(@"Array = %@", resultsArray);
for(int i = 0; i < [resultsArray count]; i++)
{
    NSDictionary *resultDictionary = [resultsArray objectAtIndex:i];
    title = [resultDictionary objectForKey:@"title"];
    abstract = [resultDictionary objectForKey:@"abstract"];
    url = [resultDictionary objectForKey:@"url"];
    byLine = [resultDictionary objectForKey:@"byline"];
    publishedDate = [resultDictionary objectForKey:@"published_date"];
    NSString *imageUrl = @"No Image";
    if([[resultDictionary objectForKey:@"multimedia"] isKindOfClass:[NSArray class]])
    {
        NSArray *multimediaArray = [resultDictionary objectForKey:@"multimedia"];
        if([multimediaArray count] < 3)
        {
            NSDictionary *multimedia3 = [multimediaArray objectAtIndex:0];
            imageUrl = [multimedia3 objectForKey:@"url"];
        }else
        {
            NSDictionary *multimedia3 = [multimediaArray objectAtIndex:3];
            imageUrl = [multimedia3 objectForKey:@"url"];
        }
    }else{
        NSLog(@"No multimedia");
    }


    News *newsObject = [[News alloc]initWithNewsName:news.newsName title:title abstract:abstract url:url byLine:byLine publishedDate:publishedDate imageUrl:imageUrl];


    NSLog(@"Title = %@", newsObject.title);
    NSLog(@"Abstract = %@", newsObject.abstract);
    NSLog(@"url = %@", newsObject.url);
    NSLog(@"byLine = %@", newsObject.byLine);
    NSLog(@"pub_date = %@", newsObject.publishedDate);
    NSLog(@"Image url = %@", newsObject.imageUrl);

    NSLog(@"Created an Object");


    [dataArray addObject:newsObject];
    NSLog(@"Object added successfully");
}

}

我从新闻API中获取数据。需要的是调度块应该从API获取数据,然后才能使用其余的代码。 但是在我的情况下,当运行调度块时,它还会执行块外的其他代码,这会使我的结果变得笨拙。 如果有人可以帮助我,我会很高兴.....

1 个答案:

答案 0 :(得分:0)

将您的以下代码放在completion handler of GET method call而不是在旁边,

NSLog(@"Filtering results");
NSArray *resultsArray = jsonDictionary[@"results"];
//NSLog(@"Array = %@", resultsArray);
for(int i = 0; i < [resultsArray count]; i++)
{
NSDictionary *resultDictionary = [resultsArray objectAtIndex:i];
title = [resultDictionary objectForKey:@"title"];
abstract = [resultDictionary objectForKey:@"abstract"];
url = [resultDictionary objectForKey:@"url"];
byLine = [resultDictionary objectForKey:@"byline"];
publishedDate = [resultDictionary objectForKey:@"published_date"];
NSString *imageUrl = @"No Image";
if([[resultDictionary objectForKey:@"multimedia"] isKindOfClass:[NSArray class]])
{
    NSArray *multimediaArray = [resultDictionary objectForKey:@"multimedia"];
    if([multimediaArray count] < 3)
    {
        NSDictionary *multimedia3 = [multimediaArray objectAtIndex:0];
        imageUrl = [multimedia3 objectForKey:@"url"];
    }else
    {
        NSDictionary *multimedia3 = [multimediaArray objectAtIndex:3];
        imageUrl = [multimedia3 objectForKey:@"url"];
    }
}else{
    NSLog(@"No multimedia");
}


News *newsObject = [[News alloc]initWithNewsName:news.newsName title:title abstract:abstract url:url byLine:byLine publishedDate:publishedDate imageUrl:imageUrl];


NSLog(@"Title = %@", newsObject.title);
NSLog(@"Abstract = %@", newsObject.abstract);
NSLog(@"url = %@", newsObject.url);
NSLog(@"byLine = %@", newsObject.byLine);
NSLog(@"pub_date = %@", newsObject.publishedDate);
NSLog(@"Image url = %@", newsObject.imageUrl);

NSLog(@"Created an Object");


[dataArray addObject:newsObject];
NSLog(@"Object added successfully");
}

这段代码应该在你把它写在外面的完成处理程序中。

更新:

 UIStoryboard *myStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
 NewsAppNewsVC *destVC = [myStoryBoard instantiateViewControllerWithIdentifier:@"NewsAppNewsVC"];
if([dataArray count] == 0)
{
NSLog(@"Array is empty");
}
else{

destVC.dataArray = dataArray;
[self.navigationController pushViewController:destVC animated:YES];
}

此代码也应该在完成处理程序中。 试试吧。 将上面的所有代码放在完成处理程序

希望这会有所帮助:)