使用block-iOS不保留变量

时间:2014-11-20 09:00:11

标签: ios mobile

-(NSMutableArray *)fetchDataForNotifications{
    __block NSMutableArray *responseArray = nil;
    NSString *requestData = [self prepareRequestJsonForNotificatios];
    NSData *postData = [requestData dataUsingEncoding:NSASCIIStringEncoding   allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    NSString* urlString = [SERVER_URL_QA stringByAppendingString:@"/api/home/notifications"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setTimeoutInterval:10.0];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setHTTPShouldHandleCookies:YES];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue   completionHandler:^(NSURLResponse *response, NSData *dataAll, NSError *error)
     {
         NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
         long int httpResponseCode = [httpResponse statusCode];

         if (error == nil && httpResponseCode == 200 && dataAll && dataAll.length > 0){
             NoticationsModel *notificationRow = [[NoticationsModel alloc]init];

             responseArray = [NSJSONSerialization JSONObjectWithData:dataAll options:NSJSONReadingMutableContainers error:nil];
             NSLog(@"HR1 %d", responseArray.count);
             for(int i =0;i<responseArray.count;i++){
                 notificationRow.fromPhotoURL = [[responseArray objectAtIndex:i] valueForKey:@"Fromphotourl"];
                 notificationRow.notificationBody = [responseArray valueForKey:@"Body"];
                 notificationRow.updatedDate = [[responseArray objectAtIndex:i] valueForKey:@"UpdatedDate"];
                 notificationRow.fromName = [responseArray valueForKey:@"FromName"];
                 [notificationArray addObject:notificationRow];
             }
         }
         else {
             NSString* errorMessage = [NSString stringWithFormat:@"Data retrived could not be   parsed. Error code %ld", (long)error.code ];
             NSLog(@"%@",errorMessage);
         }
     }];
    NSLog(@"HR %d", responseArray.count);
    return responseArray;
}

控制台中的输出是:

2014-11-20 13:45:52.667 myFriday[2888:81062] HR 0
2014-11-20 13:45:52.879 myFriday[2888:81062] HR1 10

我不明白为什么伯爵没有留在禁区外。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

使用块

你也可以利用阻止。

创建块方法以从服务器获取响应。下面我修改了方法签名以使用块调用:

- (void) fetchDataForNotifications:(void (^)(NSMutableArray *response))block {

    __block NSMutableArray *responseArray = nil;
    NSString *requestData = [self prepareRequestJsonForNotificatios];
    NSData *postData = [requestData dataUsingEncoding:NSASCIIStringEncoding   allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    NSString* urlString = [SERVER_URL_QA stringByAppendingString:@"/api/home/notifications"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setTimeoutInterval:10.0];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setHTTPShouldHandleCookies:YES];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];

    [NSURLConnection sendAsynchronousRequest:request queue:queue   completionHandler:^(NSURLResponse *response, NSData *dataAll, NSError *error)
     {
         NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
         long int httpResponseCode = [httpResponse statusCode];

         if (error == nil && httpResponseCode == 200 && dataAll && dataAll.length > 0){
             NoticationsModel *notificationRow = [[NoticationsModel alloc]init];

             responseArray = [NSJSONSerialization JSONObjectWithData:dataAll options:NSJSONReadingMutableContainers error:nil];
             NSLog(@"HR1 %d", responseArray.count);
             for(int i =0;i<responseArray.count;i++){
                 notificationRow.fromPhotoURL = [[responseArray objectAtIndex:i] valueForKey:@"Fromphotourl"];
                 notificationRow.notificationBody = [responseArray valueForKey:@"Body"];
                 notificationRow.updatedDate = [[responseArray objectAtIndex:i] valueForKey:@"UpdatedDate"];
                 notificationRow.fromName = [responseArray valueForKey:@"FromName"];
                 [notificationArray addObject:notificationRow];
             }
         }
         else {
             NSString* errorMessage = [NSString stringWithFormat:@"Data retrived could not be   parsed. Error code %ld", (long)error.code ];
             NSLog(@"%@",errorMessage);
         }

         block(responseArray);
     }];
}

调用此方法,它将等待一个块,但您需要在主线程上执行重载表操作。

[self fetchDataForNotifications:^(NSMutableArray *response) {

        // Perform operation on main thread.
        // Don't forget to set response array value to tableview datasource array.
        // e.g. self.tableArray = response;

        [self performSelectorOnMainThread:@selector(realoadTableData) withObject:nil waitUntilDone:YES];
}];


- (void) realoadTableData {
    [self.tableView reloadData];
}