返回空数组的类方法

时间:2014-01-18 23:16:58

标签: objective-c

我编写了一个类方法,它可以转换文本文件中的列数据并返回一个数组数组......只是它返回一个EMPTY数组的EMPTY数组。

+(NSArray *) initArrayWithFileContents:(NSString *) theFilePath
{
NSString *theContents = [self loadFile:theFilePath];
NSArray *theParagraphs = [self getParagraphs:theContents];

NSMutableArray *teamData = [[NSMutableArray alloc] init];       // array of team data
NSMutableArray *leagueData = [[NSMutableArray alloc] init];     // array of arrays

// set up number formatters for getting numbers from strings
NSNumberFormatter *numberStyle = [[NSNumberFormatter alloc] init];
NSNumberFormatter *positiveNumberStyle = [[NSNumberFormatter alloc] init];
[numberStyle setNumberStyle:NSNumberFormatterDecimalStyle];
[positiveNumberStyle setNumberStyle:NSNumberFormatterDecimalStyle];
[positiveNumberStyle setPositiveFormat:@"'+'#"];

// set up a date and time formatter for getting time data from strings
NSDateFormatter *timeStyle = [[NSDateFormatter alloc] init];
[timeStyle setDateStyle:NSDateFormatterNoStyle];
[timeStyle setDateFormat:@" mm:ss"];

for (NSString *currentParagraph in theParagraphs)
{
    NSArray *currentTeam = [self getcolumnarData:currentParagraph]; // get an array of strings
    for (NSString *currentItem in currentTeam)
    {
        NSNumber *currentStat = [numberStyle numberFromString:currentItem];
        if (currentStat != Nil) {
            [teamData addObject:currentStat];           // number found

        } else {
            currentStat = [positiveNumberStyle numberFromString:currentItem];
            if (currentStat != Nil) {
                [teamData addObject:currentStat];       // number with '+' sign found

            } else {
                NSDate *currentTime = [timeStyle dateFromString:currentItem];
                if (currentTime != Nil) {
                    NSNumber *theSeconds = [self calculateSeconds: currentTime];
                    [teamData addObject:theSeconds];    // time found

                } else {
                    [teamData addObject:currentItem];   // string found
                }
            }
        }
    }
    [leagueData addObject:teamData];    // add child array to end of parent array
    [teamData removeAllObjects];        // reset child array
}
NSArray *dataToReturn = [NSArray arrayWithArray:leagueData]; // convert to NSArray to return
return dataToReturn;
}

在我的调试工作中,我已经验证了NSString或NSNumber是否被添加到teamData数组的末尾,但是当向teamData添加leagueData时,会添加一个空对象。我错过了什么?

提前致谢, 布拉德

1 个答案:

答案 0 :(得分:0)

移动

NSMutableArray *teamData = [[NSMutableArray alloc] init];

进入循环:

for (NSString *currentParagraph in theParagraphs)
{
    NSMutableArray *teamData = [[NSMutableArray alloc] init];
    // ...

    [leagueData addObject:teamData];
}

环。目前,您始终将相同的数组添加到leagueData。 数组“仅”保持指向其元素的指针,因此最后是所有元素 leagueData的{​​{1}}指向同一个数组teamData(已从中删除 所有对象)。