在for循环中从NSArray中选择图像

时间:2011-04-22 12:10:56

标签: objective-c arrays macos nsimage

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

到目前为止我已经得到了这个,它只返回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;
}

感谢。

1 个答案:

答案 0 :(得分:0)

这样的“声音”更适用。

+ (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;
}