EXC_BAD_ACCESS NSDictionary出错

时间:2014-02-22 10:51:04

标签: ios objective-c json memory-management

当我从JSON文件中获取数据时,我收到错误 - > EXC_BAD_ACCESS

我没有使用ARC,这是我的代码:

    -(void)fetchedData:(NSData*)responseData
{
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    fetchedResutsArray = [json objectForKey:@"People"];

    NSLog(@"%@", fetchedResutsArray);
    [self.tableView reloadData];
}

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";
    //OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    // Configure the cell...
    NSDictionary *resultsDict = [fetchedResutsArray objectAtIndex:indexPath.row];

    cell.textLabel.text = [resultsDict objectForKey:@"prename"];

    return cell;
}

这是我的JSON-Result。我从网站上获取数据 JSON:

 {
        prename = "Tim";
        lastname = "Test";
        username = "tim23";  
    },
        {
        prename = "John";
        lastname = "Test";
        username = "johniii";  
    },
        {
        prename = "Peter";
        lastname = "Test";
        username = "tenek23";        
    }

Xcode在NSLOG中展示了这一点。

1 个答案:

答案 0 :(得分:2)

fetchedResutsArray = [json objectForKey:@"People"];

这会创建一个自动释放的对象,该对象迟早会被释放。您不得在该方法之外访问此对象。您违反了内存管理规则。

您可以保留对象,这可以解决您的问题。

[fetchedResutsArray release]; // release old instance
fetchedResutsArray = [[json objectForKey:@"People"] retain];

或者使用retain @property并使用self.fetchedResutsArray = [json objectForKey:@"People"];分配对象。 不要忘记在dealloc

中释放对象

或者只使用ARC。