将项目添加到块内的NSMutableArray中时遇到问题 [英] Trouble with adding item into an NSMutableArray inside a block
本文介绍了将项目添加到块内的NSMutableArray中时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
更新: 我刚刚发现了一个棘手的部分...如果我做这样的事情,它会起作用:
UPDATE: I just found a tricky part... if I do something like this, it works:
[_friendsArrayInBlock insertObject:@"Bla" atIndex:itemIndex];
但不是:
[_friendsArrayInBlock insertObject:friend atIndex:itemIndex];
为什么我不能添加自定义对象,但是可以添加NSString?有什么问题
Why I cannot add a custom object, but I can add NSString? What's the problem
原始部分: 在这里,您可以看到相关的代码部分:
ORIGINAL PART: Here you can see the relevant code part:
@implementation ORGFriendsTableViewController
{
NSMutableArray *_friendsArray;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_friendsArray = [NSMutableArray array];
__block NSMutableArray *_friendsArrayInBlock = _friendsArray;
[FBRequestConnection startForMyFriendsWithCompletionHandler: ^(FBRequestConnection *connection,
id result,
NSError *error) {
FBGraphObject *fbGraphObject = (FBGraphObject *)result;
NSMutableArray *userArray = fbGraphObject[@"data"];
for (FBGraphObject *user in userArray) {
ORGFBUser *friend = [[ORGFBUser alloc] initWithId:user[@"id"] name:user[@"name"] andPhotoURL:@"someurl"];
NSInteger itemIndex = 0;
[_friendsArrayInBlock insertObject:friend atIndex:itemIndex];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:itemIndex inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
此行出现问题:
[_friendsArrayInBlock insertObject:friend atIndex:itemIndex];
程序接收信号"EXC_BAD_ACCESS"
Program recieving signal "EXC_BAD_ACCESS"
我认为它与块概念有关,并从中更改了非线程安全的NSMutableArray.
I think it's related with block concept, and altering a non thread-safe NSMutableArray from it.
您知道如何解决此问题吗?
Do you have any idea how to fix this?
推荐答案
Blocks can access instance variables without using __block
(see this). Therefore this should work:
- (void)viewDidLoad
{
[super viewDidLoad];
_friendsArray = [NSMutableArray array];
[FBRequestConnection startForMyFriendsWithCompletionHandler: ^(FBRequestConnection *connection,
id result,
NSError *error) {
FBGraphObject *fbGraphObject = (FBGraphObject *)result;
NSMutableArray *userArray = fbGraphObject[@"data"];
for (FBGraphObject *user in userArray) {
ORGFBUser *friend = [[ORGFBUser alloc] initWithId:user[@"id"] name:user[@"name"] andPhotoURL:@"someurl"];
NSInteger itemIndex = 0;
[_friendsArray insertObject:friend atIndex:itemIndex];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:itemIndex inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
这篇关于将项目添加到块内的NSMutableArray中时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文