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

时间:2010-11-17 04:26:19

标签: iphone objective-c nsmutablearray

正在破坏arrayOfPerformances。

这是数组的.h:

    NSMutableArray * arrayOfPerformances;
}
@property (nonatomic, retain) NSMutableArray * arrayOfPerformances;

和.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;
}

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

2 个答案:

答案 0 :(得分: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];                                      <--

你分配+ 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

答案 1 :(得分:0)

我不认为arrayOfPerformances被破坏了。看起来你甚至没有在任何地方初始化它。