NSMutableArray不断覆盖自己,只返回一个条目

时间:2015-08-20 20:41:31

标签: objective-c

我正在编写的for循环不断覆盖自己,我需要能够返回所有值。如何让我的for循环不被覆盖?

sourceArray = [[NSMutableArray alloc] init];

for (NSString *file in sourceFiles) {


    NSString *sourceFile = [sourcePath stringByAppendingPathComponent:file];
    NSImage *image = [[NSImage alloc] initWithContentsOfFile:sourceFile];
    NSImageRep *rep = [[image representations] objectAtIndex:0];

    sourceArray = [NSMutableArray arrayWithObjects:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                                        sourceFile.lastPathComponent, @"fileName",
                                                        [NSNumber numberWithLong:rep.pixelsWide], @"width",
                                                        [NSNumber numberWithLong:rep.pixelsHigh], @"height",
                                                        nil], nil];

}

1 个答案:

答案 0 :(得分:2)

问题是[NSMutableArray arrayWithObjects:通过循环替换每次旅行中的数组。代替...

// prettier using modern clang literals...
NSDictionary *d = @{ @"fileName": sourceFile.lastPathComponent, 
                     @"width":    @(rep.pixelsWide),
                     @"height":   @(rep.pixelsHeight) };

// just add to the array we allocated outside the loop
[sourceArray addObject:[d mutableCopy]];