2013-04-19

UIImage 存放到 NSArray/NSMutableArray 內

最近學員遇到一個問題,要將 UIImage 放到 NSMutableArray 內,但是很不幸地會發生這樣的錯誤訊息:
ImageArray[5343:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

不管是從 NSBundle 或是從 NSFileManager 取得 Documents 的都一樣。

載入如下:

NSArray *directoryContent = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:nil];
NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:0];

for (NSString *imagePath in directoryContent) {
    UIImage *img = [UIImage imageNamed:imagePath];
    [items addObject:img];
}
NSLog(@"imagesArray:%@", items);

可是執行之後,就會得到上述的錯誤訊息。

錯誤的原因就在這句:
UIImage *img=[UIImage imageNamed: imagePath];

只要改成
UIImage *img = [UIImage imageWithContentsOfFile:imagePath];

錯誤就可以修正


最後正確的程式碼如下:

NSArray *directoryContent = [[NSBundle mainBundlepathsForResourcesOfType:@"png" inDirectory:nil];
NSMutableArray *items = [[NSMutableArray allocinitWithCapacity:0];

for (NSString *imagePath in directoryContent) {
    UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
    [items addObject:img];
}
NSLog(@"imagesArray:%@", items);


善用你在 Xcode 的 Option+Click,你就可以找到答案了:

+ (UIImage *)imageWithContentsOfFile:(NSString *)path
Creates and returns an image object by loading the image data from the file at the specified path.
This method does not cache the image object.

+ (UIImage *)imageNamed:(NSString *)name
Returns the image object associated with the specified filename.
This method looks in the system caches for an image object with the specified name and returns that object if it exists


下載範例檔案
.

沒有留言:

張貼留言