数组计数错误

时间:2014-02-07 11:11:56

标签: ios iphone objective-c

我有两种方法。从第一种方法我发送数组到第二种方法。在我的第一个方法[array count]值是2.但是在seconf方法中,值是1.但是在两个方法中它应该是相同的。我知道这是一个愚蠢的错误。但我不明白我在哪里做错了。

第一种方法:

-(void)uploadOverlayManually: (NSMutableArray *)path{

NSFileManager *fileManager = [NSFileManager defaultManager];

NSLog(@"Array count #1: %d",[path count]);

for (int i =0; i < [path count]; i++) {

    imagePath = [path objectAtIndex:i];

    NSString *infoPath = [[imagePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"info"];
    NSData *infoData = [[NSMutableData alloc] initWithContentsOfFile:infoPath];

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:infoData];
    MediaInformation *currentInfo = [unarchiver decodeObjectForKey:@"info"];
    [unarchiver finishDecoding];

    UIImage *baseImage = [UIImage imageWithContentsOfFile:imagePath];
    NSData *data = [root addImageOverlay:baseImage withInfo:currentInfo andPath:imagePath];

    [data writeToFile:imagePath atomically:YES];

    fileUpload = [[NSMutableArray alloc] init];

    [fileUpload addObject:imagePath];

}

[self upload:fileUpload];

}

第二种方法:

-(void)upload:(NSArray*)filePaths{

if (![[DBSession sharedSession] isLinked]) {

    [[DBSession sharedSession] linkFromController:root]; //root
}

NSLog(@"Array count #2: %d",[filePaths count]);

}

3 个答案:

答案 0 :(得分:1)

这一行

fileUpload = [[NSMutableArray alloc] init];
循环中的

重新创建数组。

它应该在循环之前,所以你在每次迭代时添加一个对象。

答案 1 :(得分:0)

您在每个循环上实例化一个新数组,因此它总是只有1

要实现预期的行为使用(从循环中移出实例化):

-(void)uploadOverlayManually: (NSMutableArray *)path{

NSFileManager *fileManager = [NSFileManager defaultManager];

NSLog(@"Array count #1: %d",[path count]);

fileUpload = [[NSMutableArray alloc] init];

for (int i =0; i < [path count]; i++) {

    imagePath = [path objectAtIndex:i];

    NSString *infoPath = [[imagePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"info"];
    NSData *infoData = [[NSMutableData alloc] initWithContentsOfFile:infoPath];

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:infoData];
    MediaInformation *currentInfo = [unarchiver decodeObjectForKey:@"info"];
    [unarchiver finishDecoding];

    UIImage *baseImage = [UIImage imageWithContentsOfFile:imagePath];
    NSData *data = [root addImageOverlay:baseImage withInfo:currentInfo andPath:imagePath];

    [data writeToFile:imagePath atomically:YES];

    [fileUpload addObject:imagePath];

}

[self upload:fileUpload];

答案 2 :(得分:0)

您正在循环内部分配数组,请在viewDidLoad或仅调用一次的任何函数中分配它。