我正在使用 ARC 并以 iOS 5 为目标。我已经在我的 View Controller 的一个 header 中声明了一个 NSMutableArray ivar,在 viewDidLoad 中对其进行了初始化,并且我试图在我的一些 View Controller 的方法中对其进行操作。但是,它的行为非常奇怪。当我向它发送消息,如“addObject:”,或尝试将其设置为等于在方法的本地范围内创建的 NSMutableArray 时,它会将消息发送到我声明的其他 ivars。
例如,我不断收到的错误之一是 -[PullToRefreshView count]: unrecognized selector sent to instance。 PullToRefreshView 是我的另一个 ivar,但在我的代码中,我清楚地将计数消息发送到我的 NSMutableArray ivar。当尝试向 ivar NSMutableArray 添加一个对象时,它的计数(在调试器中)保持为 0。我一直在我的代码中搜索我可能忽略的东西,但它看起来像是某种 ARC 内存管理侥幸。有任何想法吗?这是我的代码的相关区域:
MyViewController.h
@interface MyViewController : UIViewController
{
PullToRefreshView *pull;
NSMutableArray *commentsSharesMerged;
}
@property (nonatomic, retain) PullToRefreshView *pull;
@property (nonatomic, retain) NSMutableArray *commentsSharesMerged;
- (void)refreshComments;
- (void)refreshShares;
@end
MyViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
commentsSharesMerged = [[NSMutableArray alloc] init];
pull = [[PullToRefreshView alloc] initWithScrollView:(UIScrollView *)self.suggestionTable];
[pull setDelegate:self];
[self.suggestionTable addSubview:pull];
}
- (void)refreshComments
{
NSURL *url = [NSURL URLWithString:@"http://example.com/comments.json"];
__unsafe_unretained __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
NSString *responseString = [request responseString]; // Use when fetching text data
NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [[CJSONDeserializer deserializer] deserialize:responseData error:nil];
NSLog(@"Connection JSON: %@", jsonObject);
NSMutableArray *commentsArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [jsonObject count]; i++)
{
NSDictionary *currentCommentData = [jsonObject objectAtIndex:i];
Comment *comment = [[Comment alloc] init];
comment.identifier = [[currentCommentData objectForKey:@"id"] intValue];
comment.firstName = [currentCommentData objectForKey:@"first_name"];
comment.lastName = [currentCommentData objectForKey:@"last_name"];
comment.commentText = [currentCommentData objectForKey:@"comment"];
[commentsArray addObject:comment];
}
self.commentsSharesMerged = [commentsArray mutableCopy];
// I've also tried to add the object using something like this
//for (Comment *comment in commentsArray)
// [commentsSharesMerged addObject:comment];
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"%@", error);
}];
[request startAsynchronous];
}
最佳答案
我找到了解决问题的方法。它可以归因于 LLDB 调试中的某种内存错误。我将我的方案移至 GDB,这解决了我的 ivar 分配问题。
关于ios - 尝试添加对象时使用 ARC 的奇怪 NSMutableArray ivar 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9665701/