为什么NSMutableArray在这个循环中被销毁?

Mau*_*imo 0 iphone objective-c nsmutablearray

这是arrayOfPerformances被破坏了.

这是数组的.h:

    NSMutableArray * arrayOfPerformances;
}
@property (nonatomic, retain) NSMutableArray * arrayOfPerformances;
Run Code Online (Sandbox Code Playgroud)

和.m有循环:

[dataArray release];
[dataDictionary release];
dataArray = [[NSMutableArray alloc] init];
dataDictionary = [[NSMutableDictionary alloc] init];

NSDate * CurrentDate = start;
int i = 0;

NSMutableArray * arrayOfPerformancesForCurrentDate = [[NSMutableArray alloc] init];
while(YES)
{
    i = 0;
    if ([arrayOfPerformancesForCurrentDate count] > 0)
    {
        [arrayOfPerformancesForCurrentDate removeAllObjects];   
    }

    for (i; i < self.arrayOfPerformances.count; i++)
    {
        Performance * performanceItem = [[Performance alloc] init]; 
        performanceItem = [self.arrayOfPerformances objectAtIndex:i];

        NSString * sPerformanceDate = [performanceItem.sDate substringToIndex:10];
        NSString * sCurrentDate = [CurrentDate dateDescription];

        if([sPerformanceDate isEqualToString:sCurrentDate])
        {
            [arrayOfPerformancesForCurrentDate addObject:performanceItem];
        }

        [performanceItem release];
    }

    if ([arrayOfPerformancesForCurrentDate count] >= 1)
    {
        [dataDictionary setObject:arrayOfPerformancesForCurrentDate forKey:CurrentDate];
        [dataArray addObject:[NSNumber numberWithBool:YES]];
    }
    else
    {
        [dataArray addObject:[NSNumber numberWithBool:NO]];
    }

    TKDateInformation info = [CurrentDate dateInformation];
    info.day++;
    CurrentDate = [NSDate dateFromDateInformation:info];
    if([CurrentDate compare:end]==NSOrderedDescending) break;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.我不明白为什么会这样?

小智 5

这部分看起来不正确:

Performance * performanceItem = [[Performance alloc] init];     <--
performanceItem = [self.arrayOfPerformances objectAtIndex:i];   <--

NSString * sPerformanceDate = [performanceItem.sDate substringToIndex:10];
NSString * sCurrentDate = [CurrentDate dateDescription];

if([sPerformanceDate isEqualToString:sCurrentDate])
{
    [arrayOfPerformancesForCurrentDate addObject:performanceItem];
}

[performanceItem release];                                      <--
Run Code Online (Sandbox Code Playgroud)

你分配+ init performanceItem但是然后将它设置为arrayOfPerformances中的一个对象,然后释放它(当它指向arrayOfPerformances中的对象时).

将该部分更改为:

Performance *performanceItem = [self.arrayOfPerformances objectAtIndex:i];

NSString * sPerformanceDate = [performanceItem.sDate substringToIndex:10];
NSString * sCurrentDate = [CurrentDate dateDescription];

if([sPerformanceDate isEqualToString:sCurrentDate])
{
    [arrayOfPerformancesForCurrentDate addObject:performanceItem];
}

//don't release performanceItem
Run Code Online (Sandbox Code Playgroud)