【发布时间】: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