【问题标题】:Selecting an image from an NSArray in a for loop在 for 循环中从 NSArray 中选择图像
【发布时间】:2011-04-22 12:10:55
【问题描述】:

所以我有这些对应于一个项目的数字代码,我需要为每个项目获取一个图像以显示在表格中。 (所有表格等都已排序,仅此图像选择..)

到目前为止,我已经得到了这个,它只返回 blockNotFound.png。我需要它为每个请求的“itemId”返回相应的“block-X.png”。

+ (NSImage *)imageForItemId:(uint16_t)itemId {
    NSSize          itemImageSize = NSMakeSize(32, 32);
    NSImage         *output = [[NSImage alloc] initWithSize:itemImageSize];
    NSString        *path = [[NSBundle mainBundle] bundlePath];
    NSFileManager   *fm = [NSFileManager defaultManager];
    NSArray         *imageArray = [fm contentsOfDirectoryAtPath:path error:nil];

    for (id object in imageArray) {
        NSString *imagePath = [NSString stringWithFormat:@"%@/block-%d.png",path,itemId];
        // This NSLog does list all files in imagePath.
        // NSLog(imagePath);
        if ([fm fileExistsAtPath:imagePath]) {
            output = [NSImage imageNamed:imagePath];
        } else {
            output = [NSImage imageNamed:@"blockNotFound.png"];
        }
    }

    return output;
}

谢谢。

【问题讨论】:

  • for 循环毫无意义。您没有在循环内使用object,所以您可能根本没有循环。
  • 那么我会用什么替换object
  • 你要做的第一件事就是理解你的代码。你为什么首先写循环?它应该做什么?为什么你认为你需要它?
  • 应该遍历path中的所有文件(图片),然后通过它们过滤itemId,如果output存在,设置它,如果不存在,设置它为blockNotFound.png .
  • 那么您是否意识到循环在这里没有帮助?您只是多次执行相同的代码块,总是得到相同的结果。根本不需要循环,因为[fm fileExistsAtPath:imagePath] 已经循环了您感兴趣的所有文件。您也不需要imageArray。虽然我们这样做了,但首先创建一个 NSImage(第 3 行)然后为变量分配一个不同的对象是错误的。

标签: objective-c arrays macos nsimage


【解决方案1】:

这样的“听起来”更适用。

+ (NSImage *)imageForItemId:(NSUInteger)itemId {

    NSSize          itemImageSize = NSMakeSize(32, 32); // use it to set the size later
    NSImage         *output;
    NSFileManager   *fm = [NSFileManager defaultManager];



    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *imagePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"block-%d.png",itemId]];

    if ([fm fileExistsAtPath:imagePath]) {
        output = [NSImage imageNamed:imagePath];
    } 
    else {
        output = [NSImage imageNamed:@"blockNotFound.png"];
    }


    return output;
}

【讨论】:

  • 没有理由使用for循环,也许这就是为什么你不在其块中的任何地方使用object ;)
  • 这仍然将所有图像设置为 blockNotFound.png。 :3
  • 显然没有与imagePath匹配的图片。
猜你喜欢
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 2013-06-02
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
相关资源
最近更新 更多