Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/93.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从completionHandler返回NSMutableArray(目标C)_Ios_Objective C_Post_Nsmutablearray_Nsurlsession - Fatal编程技术网

Ios 从completionHandler返回NSMutableArray(目标C)

Ios 从completionHandler返回NSMutableArray(目标C),ios,objective-c,post,nsmutablearray,nsurlsession,Ios,Objective C,Post,Nsmutablearray,Nsurlsession,我确实向web服务发布了请求并得到了响应。我将响应转换为NSMutableArray。我在NSURLSessionDataTask中的响应,现在我想返回NSMUTABLEARRY,以便在NSURLSessionDataTask之外使用。这是我的密码: NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"url"]]; [

我确实向web服务发布了请求并得到了响应。我将响应转换为NSMutableArray。我在NSURLSessionDataTask中的响应,现在我想返回NSMUTABLEARRY,以便在NSURLSessionDataTask之外使用。这是我的密码:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:@"url"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSString *postString = @"params";

    NSString *postLength = [NSString stringWithFormat:@"%lu", ( unsigned long )[postString length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length" ];

    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];



    NSURLSessionDataTask *task = [[self getURLSession] dataTaskWithRequest:request completionHandler:^( NSData *data, NSURLResponse *response, NSError *error )
                                  {
                                      dispatch_async( dispatch_get_main_queue(),
                                                     ^{
                                                         NSDictionary *dicData = [NSJSONSerialization
                                                                                  JSONObjectWithData:data
                                                                                  options:NSJSONReadingAllowFragments
                                                                                  error:nil];

                                                        NSDictionary *values = [dicData valueForKeyPath:@"smth"];

                                                         NSArray * dataArr = [dicData objectForKey:@"smth"];
                                                         NSArray * closeArr = [values objectForKey:@"0"];

                                                         NSUInteger  dataCount = [dataArr count] ;
                                                         NSUInteger  closeCount = [closeArr count] ;

                                                         NSMutableArray * newData = [NSMutableArray new] ; //<-- THIS ARRAY

                                                         for(int i = 0 ; i<dataCount && i<closeCount ; i++)
                                                         {
                                                             NSMutableDictionary * temp = [NSMutableDictionary new] ;
                                                             NSString * dataString = [dataArr objectAtIndex:i];
                                                             NSString * closeString = [closeArr objectAtIndex:i];
                                                             [temp setObject:dataString forKey:@"smth"];
                                                             [temp setObject:closeString forKey:@"smth"];

                                                             [newData addObject:temp];
                                                         }

                                                         NSLog(@"%@", newData);
                                                     } );
                                  }];
    [task resume]; 
当我试图在NSURLSessionDataTask中实现这段代码时,图表不会出现。所以我需要在外部返回NSMutableArray(其中我的数据采用适当的json格式)

我该怎么做?有什么想法吗?
谢谢大家!

不能在完成处理程序中添加return语句,因为如果会话返回错误,可能不会调用该语句。事实上,如果您尝试这样做,Xcode将给您一个“不兼容的指针类型”错误

我发现最好的解决方法是将newData数组设置为属性,并使其可用于类中的其他方法。如果在url会话任务结束时某个特定方法需要处理此数组,则可以从完成处理程序调用该方法或使用通知

或者,如果出于某种原因不想使用类属性,可以使用NSNotificationCenter,并将新数据传递给notification对象中的侦听器

编辑:使用属性编码示例

如果需要完成块之外的新数据,一种简单的方法是将数组声明为属性。这不是唯一的方法,也可能不是最好的方法。但这并没有给代码增加太多的复杂性。 您可以在.m类文件中声明newData数组:

@interface "whatever class you are using"
@property (nonatomic, strong)  NSMutableArray *newData;
@end
您可以在viewDidLoad方法中初始化数组:

- (void)viewDidLoad {
    _newdata = [[NSMutableArray alloc] init];
}
在完成块中,删除初始化并向数组中添加数据

//NSMutableArray * newData = [NSMutableArray new] ; // REMOVE THE INTIALIZATION
for(int i = 0 ; i<dataCount && i<closeCount ; i++) {
    NSMutableDictionary * temp = [NSMutableDictionary new] ;
    NSString * dataString = [dataArr objectAtIndex:i];
    NSString * closeString = [closeArr objectAtIndex:i];
    [temp setObject:dataString forKey:@"smth"];
    [temp setObject:closeString forKey:@"smth"];
    [_newData addObject:temp];
}

在块中返回值是最糟糕的想法。此代码是异步的,在这种情况下,必须使用块或委托将数据从一个对象传递到另一个对象。此外,请进一步解释该代码的用例。@Adeel我更新了我的问题,请看一看。你能帮我写代码吗(不是为我写的)?我指的是一些关于它的提示、教程或有用的文章。我试着自己做,但没有成功。非常感谢。但它不起作用。如果我使用SQLite呢?我的意思是将我的数组保存在SQLite中,然后在我想要的任何地方调用它。你能详细说明一下为什么它不工作吗?您试图在哪里使用阵列?如果你展示其余的代码,这将有助于我们理解你想要实现的目标。好吧,我不是ShinobiControls的专家,所以我不能告诉你是否有什么东西坏了。但是,我认为应该将代码中传递数据数组到图表的部分移动到完成块中。请看我编辑的答案。在NSLog(@“%@”,newData)中记录数据时;您在输出中看到所需的数据了吗?没有,我在NSLog中没有看到任何结果。我得到的消息与此类似:
2016-11-23 10:21:59.885 ProjectName[1184:20780]()
我试图将其移动到完成块内,但它不起作用(即使使用本地json)。这就是为什么我想把它放在外面。
//NSMutableArray * newData = [NSMutableArray new] ; // REMOVE THE INTIALIZATION
for(int i = 0 ; i<dataCount && i<closeCount ; i++) {
    NSMutableDictionary * temp = [NSMutableDictionary new] ;
    NSString * dataString = [dataArr objectAtIndex:i];
    NSString * closeString = [closeArr objectAtIndex:i];
    [temp setObject:dataString forKey:@"smth"];
    [temp setObject:closeString forKey:@"smth"];
    [_newData addObject:temp];
}
- (void)loadChartData {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"url"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSString *postString = @"params";

    NSString *postLength = [NSString stringWithFormat:@"%lu", ( unsigned long )[postString length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length" ];

    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionDataTask *task = [[self getURLSession] dataTaskWithRequest:request completionHandler:^( NSData *data, NSURLResponse *response, NSError *error ) {
        dispatch_async( dispatch_get_main_queue(), ^{
            NSDictionary *dicData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

            NSDictionary *values = [dicData valueForKeyPath:@"smth"];
            NSArray * dataArr = [dicData objectForKey:@"smth"];
            NSArray * closeArr = [values objectForKey:@"smth0"];
            NSUInteger  dataCount = [dataArr count] ;
            NSUInteger  closeCount = [closeArr count] ;
            NSMutableArray * newData = [NSMutableArray new] ;

            for(int i = 0 ; i<dataCount && i<closeCount ; i++) {
                NSMutableDictionary * temp = [NSMutableDictionary new] ;
                NSString * dataString = [dataArr objectAtIndex:i];
                NSString * closeString = [closeArr objectAtIndex:i];
                [temp setObject:dataString forKey:@"smth"];
                [temp setObject:closeString forKey:@"smth"];
                [newData addObject:temp];
            }

            NSLog(@"%@", newData);

            _timeSeries = [NSMutableArray new];
            NSString* filePath = [[NSBundle mainBundle] pathForResource:@"AppleStockPrices" ofType:@"json"];
            NSData* json = [NSData dataWithContentsOfFile:filePath];
            NSArray* data = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingAllowFragments error:nil];
            for (NSDictionary* jsonPoint  in data) {
                SChartDataPoint* datapoint = [self dataPointForDate:jsonPoint[@"smth"] andValue:jsonPoint[@"smth"]];
                [_timeSeries addObject:datapoint];
            }
       });
    }];
    [task resume];

// Code here has a good chance of being executed before the completion block is complete
//    _newdata = [[NSMutableArray alloc] init];    
//    NSLog(@"%@", _newdata);
}