這是我想要實現的。 1.搜索所有的文件2.找到所有.jpg文件的搜索3.在所有.jpg文件路徑保存到NSMutableArray的目標c:在線程中將對象添加到NSMutableArray時出錯
這裏是代碼:
創造了NSMutableArray中:
NSMutableArray *jpgFiles = [[[NSMutableArray alloc]init]autorelease];
搜索下(/用戶/)路徑(開始NSThread在這裏)所有的父文件夾:
NSString* filePath = [url path]; NSArray *dirFiles = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:filePath error:nil]; if([dirFiles count]!=0) { for (int j=0; j<[dirFiles count]; j++) { NSString* pathExtension = [[dirFiles objectAtIndex:j] pathExtension]; //if extension is null, we forwards to next level. if ([pathExtension isEqualTo:@""]) { @autoreleasepool { [NSThread detachNewThreadSelector:@selector(searchingPicture:) toTarget:self withObject:[filePath stringByAppendingPathComponent:[dirFiles objectAtIndex:j]]]; } } else { //if find jpg in this level, save into array if([pathExtension isEqualTo:@"JPG"]) { [jpgFiles addObject:[filePath stringByAppendingPathComponent:[dirFiles objectAtIndex:j]]]; } } } }
繼續搜索子文件夾的休息和保存正確的文件路徑分爲數組:
-(void)searchingPicture:(NSString*)path { NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; NSURL *directoryURL = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey]; NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:directoryURL includingPropertiesForKeys:keys options:0 errorHandler:^(NSURL *url, NSError *error) { // Handle the error. // Return YES if the enumeration should continue after the error. return YES; }]; for (NSURL *url in enumerator) { NSError *error; NSNumber *isDirectory = nil; if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) { // handle error } else if (! [isDirectory boolValue]) { // No error and it’s not a directory; do something with the file if([[[url path] pathExtension]isEqualTo:@"JPG"]) { //This line gives me error !!! [jpgFiles addObject:[url path]]; } } } }
錯誤:(在開始時,它工作正常,並保存許多不同的文件轉換成數組,但節省約50個文件後,它開始在最後給我錯誤和崩潰)。
這裏是正確的元素添加到數組:
以下是錯誤消息:
-[NSPathStore2 addObject:]: unrecognized selector sent to instance 0x10011d4d0
然而,甚至發生這種錯誤,它仍保持節省一些的路徑然後它會拋出另一個錯誤:
An uncaught exception was raised
你可以告訴我如何解決嗎?謝謝 !!
該錯誤指示內存管理問題。也許問題是在'jpgFiles'上使用'autorelease'。當你創建它時,不要使用'autorelease',而是在你真正完成陣列時調用'release'。 – rmaddy
你是對的。謝謝 !!!! :]但是爲什麼我應該使用release而不是autorelease? –
這是一個很大的問題。這個過於簡單的原因是,在當前運行循環結束時會清除自動釋放的對象。查看「NSObject autorelease」的文檔。應該有一些其他文檔的鏈接可以深入討論。 – rmaddy