在方法块中使用方法声明中的variables时,“variables不可分配(缺less__blocktypes说明符)”错误

我正在开发一个小的IO应用程序,从服务器中检索信息,我发现了非常有用的NSURLSessionDataTask。 首先我使用了@property (nonatomic, strong) NSMutableArray *objectArray; 我在我的方法中调用:

  - (void) createObjectsArrayFromUrl: (NSString *) url { NSURL *URL = [NSURL URLWithString:url]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { if(error) { //error handling } dispatch_async(dispatch_get_main_queue(), ^{ NSMutableDictionary *jsonDataDictionary = [objectModel getJsonData]; self.objectArray = [objectModel arrayFromDictionary:jsonDataDictionary]; [[self collectionView] reloadData]; }); }]; [task resume]; } 

一切顺利。 现在我想创build一个通用的方法,为更多的数组,我想通过传递数组到方法,并更新里面,如下所示:

 - (void) createObjectsArrayFromUrl: (NSString *) url inArray: (NSMutableArray *) objectArray{ NSURL *URL = [NSURL URLWithString:url]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { if(error) { //error handling } dispatch_async(dispatch_get_main_queue(), ^{ NSMutableDictionary *jsonDataDictionary = [objectModel getJsonData]; objectArray = [objectModel arrayFromDictionary:jsonDataDictionary]; [[self collectionView] reloadData]; }); }]; [task resume]; } 

但它给了我在下面一行标题中的错误: objectArray = [objectModel arrayFromDictionary:jsonDataDictionary]; 我不知道该怎么做 所以我的想法是,而不是像我以前一样为每个数组创build一个方法,我想要传递数组作为variables,并在方法中更新它。 如何做到这一点? 谢谢。

代替

 objectArray = [objectModel arrayFromDictionary:jsonDataDictionary]; 

尝试

 [objecyArray removeAllObjects]; [objectArray addObjectsFromArray:[objectModel arrayFromDictionary:jsonDataDictionary]]; 

这是因为进来的variables前面没有__block ,因此允许它在一个块中使用,这只适用于局部variables而不是参数。 我相信__block这样做是为了在块内引用。

如果你想访问块中的variables,那么你应该首先将它分配为块,如__block NSArray *arr; 。 那么你可以在完成处理程序中以块的方式访问该variables。

在你的代码中,你可以在方法体的开始处添加一行,

 __block NSArray *arr = objectArray; 

然后使用这个块,

  arr = [objectModel arrayFromDictionary:jsonDataDictionary]; 

希望这会帮助:)