Cocoa & Objective-C에 폴더가 있는지 확인하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/99395

  •  01-07-2019
  •  | 
  •  

문제

Objective-C를 사용하여 Cocoa에 폴더(디렉토리)가 있는지 확인하는 방법은 무엇입니까?

도움이 되었습니까?

해결책

사용 NSFileManager'에스 fileExistsAtPath:isDirectory: 방법.Apple 문서 보기 여기.

다른 팁

파일 시스템 확인과 관련하여 NSFileManager.h에 있는 Apple의 좋은 조언은 다음과 같습니다.

"작업이 성공할 것인지 미리 알아내는 것보다 작업(예: 파일 로드 또는 디렉터리 생성)을 시도하고 오류를 우아하게 처리하는 것이 훨씬 낫습니다.파일 시스템의 현재 상태나 파일 시스템의 특정 파일을 기반으로 동작을 예측하려는 시도는 파일 시스템 경쟁 조건에 직면했을 때 이상한 동작을 조장하는 것입니다."

[NSFileManager 파일ExistsAtPath:isDirectory:]

Returns a Boolean value that indicates whether a specified file exists.

- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory

Parameters
path
The path of a file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath, or this method will return NO.

isDirectory
Upon return, contains YES if path is a directory or if the final path element is a symbolic link that points to a directory, otherwise contains NO. If path doesn’t exist, the return value is undefined. Pass NULL if you do not need this information.

Return Value
YES if there is a file or directory at path, otherwise NO. If path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file or directory at the link destination.

NSFileManager는 파일 관련 API를 찾는 가장 좋은 장소입니다.필요한 특정 API는 다음과 같습니다. - fileExistsAtPath:isDirectory:.

예:

NSString *pathToFile = @"...";
BOOL isDir = NO;
BOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:pathToFile isDirectory:&isDir];

if(isFile)
{
    //it is a file, process it here how ever you like, check isDir to see if its a directory 
}
else
{
    //not a file, this is an error, handle it!
}

당신이 가지고 있다면 NSURL 다음과 같이 반대하다 path, 경로를 사용하여 변환하는 것이 좋습니다 NSString.

NSFileManager*fm = [NSFileManager defaultManager];

NSURL* path = [[[fm URLsForDirectory:NSDocumentDirectory 
                           inDomains:NSUserDomainMask] objectAtIndex:0]                           
                                 URLByAppendingPathComponent:@"photos"];

NSError *theError = nil;
if(![fm fileExistsAtPath:[path path]]){
    NSLog(@"dir doesn't exists");
}else
    NSLog(@"dir exists");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top