首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSMutableArray一直覆盖自己,并且只返回一个条目。

NSMutableArray一直覆盖自己,并且只返回一个条目。
EN

Stack Overflow用户
提问于 2015-08-20 20:41:30
回答 1查看 18关注 0票数 0

我正在编写的for循环一直覆盖自己,我需要能够返回所有的值。如何防止for循环覆盖其自身?

代码语言:javascript
复制
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];

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-20 20:45:48

问题是在每次遍历循环时,[NSMutableArray arrayWithObjects:都会替换数组。而是..。

代码语言:javascript
复制
// 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]];
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32127987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档