开发者

Selecting an image from an NSArray in a for loop

开发者 https://www.devze.com 2023-02-27 19:08 出处:网络
So I\'ve got these number codes which correspond to an item, and I need to get an image for each item to display in a table. (All 开发者_如何学Cthe table etc is sorted, just this image selection..)

So I've got these number codes which correspond to an item, and I need to get an image for each item to display in a table. (All 开发者_如何学Cthe table etc is sorted, just this image selection..)

I've got this so far, which only returns the blockNotFound.png. I need it to return the corresponding 'block-X.png' for each 'itemId' requested.

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

Thanks.


Something like this "sounds" more applicable.

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

精彩评论

暂无评论...
验证码 换一张
取 消