0

我有一个 ViewController 定义如下:

@interface SectionController : UITableViewController {
   NSMutableArray *sections;
}
- (void) LoadSections;

当调用 LoadSection 时,它会调用 NSURLConnection 来加载一个 url,然后调用

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    [connection release];
    [responseData release];

    NSDictionary *results = [responseString JSONValue];
    NSMutableArray *jSections = [results objectForKey:@"Items"];
    sections = [NSMutableArray array];

    for (NSArray* jSection in jSections)
    {
        Section* section = [Section alloc];
        section.Id = [jSection objectForKey:@"Id"];
        section.Description = [jSection objectForKey:@"Description"];
        section.Image = [jSection objectForKey:@"Image"];
        section.Parent = [jSection objectForKey:@"Parent"];
        section.ProductCount = [jSection objectForKey:@"ProductCount"];
        [sections addObject:section];
        [section release];
    }

    [jSections release];
    [results release];

    [delegate sectionsLoaded];

    [self.view reloadData];
}

数据解析正确,现在我的部分充满了许多项目。

调用 [self.view reloadData] 会强制对委托方法 cellForRowAtIndexPath 进行回调,然后该方法应该将数据呈现到单元格中,但是此时现在再次为零。

有人可以指出我的错误吗?我必须承认我是目标 c 的新手,这可能是一个指针问题。需要做的是在调用 reloadData 后保留部分的值。

非常感谢。

4

2 回答 2

1

看到新代码问题很明显:

sections = [NSMutableArray array];

应该成为

[sections release];
sections = [[NSMutableArray alloc] init];

请注意,该数组不会再次变为“nil”,而是被释放,并且您得到一个无效的引用,这可能(应该)在取消引用时产生崩溃。

我建议你阅读一些关于引用计数内存管理的文章,因为如果你是 Objective-C 的新手,这可能并不明显,并且经常导致错误(即:自动释放根本不是魔法)

于 2010-10-09T16:46:13.553 回答
0

在这里避免所有内存泄漏的最佳方法就是简单地使用@property (nonatomic, retain) NSMutableArray *sections;属性,您可以确保所有男性管理工作都将由系统正确管理。只是不要忘记在执行 setSections: 时属性保留值,因此您需要在此处传递自动释放的对象。

self.sections = [NSMutableArray array];

...

[self.sections addObject:section];

此外,为了避免所有问题,请尝试使所有应该仅在此方法中自动释放的对象。像这样:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];

NSDictionary *results = [responseString JSONValue];
NSMutableArray *jSections = [results objectForKey:@"Items"];
self.sections = [NSMutableArray array];

for (NSArray* jSection in jSections) {
    Section* section = [[[Section alloc] init] autorelease];
    section.Id = [jSection objectForKey:@"Id"];
    section.Description = [jSection objectForKey:@"Description"];
    section.Image = [jSection objectForKey:@"Image"];
    section.Parent = [jSection objectForKey:@"Parent"];
    section.ProductCount = [jSection objectForKey:@"ProductCount"];
    [self.sections addObject:section];
}

[delegate sectionsLoaded];

[self.view reloadData];

}

而且你试图释放的大多数对象已经自动释放:传递给你的方法的所有参数都不应该手动释放,检查我认为 JSONValue 也应该返回自动释放的对象以及你通过枚举或调用 objectForKey 获得的任何东西:

于 2012-12-17T19:40:53.710 回答