NSArray早早发布

Col*_*ole 1 iphone memory-management nsarray

当我向下滚动UITableView时,我的iPhone应用程序崩溃了.我将NSZombieEnabled设置为YES,并发现我用来填充表的NSArray正在以某种方式被释放.

#import "RootViewController.h"

@implementation RootViewController
@synthesize flashsets;

- (void)viewDidLoad
{
        //Unrelated code removed from this post
        NSString *listofsetsstring = [[NSString alloc]
                                          initWithContentsOfFile:pathtosetsdata
                                          encoding:NSUnicodeStringEncoding
                                          error:&error];
        flashsets = [listofsetsstring componentsSeparatedByString:@"\n"];
        [super viewDidLoad];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [flashsets count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    }

    // Configure the cell.
    NSLog(@"IndexPath.row = %i", indexPath.row);
    cell.textLabel.text = [flashsets objectAtIndex:indexPath.row]; <<<< CRASH HERE!!

    return cell;
}

@end
Run Code Online (Sandbox Code Playgroud)

我正在message sent to deallocated instance 0x4ebae20加粗线.在我使用的.h中@property (nonatomic, retain) NSArray *flashsets;,我认为保留部分应该避免解除分配.

我如何防止它这样做?

小智 5

问题是:

flashsets = [listofsetsstring componentsSeparatedByString:@"\n"];
Run Code Online (Sandbox Code Playgroud)

改为

flashsets = [[listofsetsstring componentsSeparatedByString:@"\n"] retain];
Run Code Online (Sandbox Code Playgroud)

编辑:只有在使用setter时才使用retain in属性,因此只有在使用以下行时才能使用:

[self setFlashsets:[listofsetsstring componentsSeparatedByString:@"\n"]];
Run Code Online (Sandbox Code Playgroud)