2011-07-06 2 views
2

NSData 개체로 데이터를 읽으려고 할 때 지정된 경로에 파일이 있는지 확인해야합니까? 지금 당장은하지 않지만 코드에서 데이터가 채워지는 배열은 nil로 설정되고 나중에 배열이 nil인지 응용 프로그램 검사에서 확인할 수 있기 때문에 코드가 작동합니다. 하지만 코드가 아마도 "못생긴"것이라고 생각하고 코드를 주석으로 처리 한 경우처럼 더 잘 작동합니다.Objective-C NSData initWithContentsOfFile, 파일이 존재하는지 확인 하시겠습니까?

NSData *codedData = [[NSData alloc] initWithContentsOfFile:[CareersParser dataFilePath]]; 

    /* 
    if (codedData != nil) { 
     //do the below (not commented out code) 
    } else { 

     //file doesn't exist at the given path 
     [codedData release]; 
     return nil; 
    } 
    */ 

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:codedData]; 
    NSArray *careers = [unarchiver decodeObjectForKey:kDataKey];  
    [unarchiver finishDecoding]; 

    NSMutableArray *ids = [[NSMutableArray alloc] init]; 

    for (Career *career in careers) { 
     [ids addObject:[career id]]; 
    } 

    // Sort the array in an orderly fashion 
    NSArray *sortedIds = [ids sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 

    // Release allocated memory 
    [ids release]; 
    [unarchiver release]; 
    [codedData release]; 

    return sortedIds; 

답변

2

나는 else 절을 ​​없애기 위해 if 문을 뒤집을 것이다.

if (nil == codedDate) { 
    [codedData release]; 
    return nil; 
} 

... Do the rest of your code 

애플은 당신이 제안처럼 데이터로드 등의 작업을 수행하려고한다 here 제안합니다. 당신이하려고하지 않는 한 [[NSManager defaultManager] fileExistsAtPath:path] 경쟁 조건을 소개하지 않습니다.

+0

'fileExistsAtPath' 메소드를 사용할 때 어떻게 경쟁 상황이 발생합니까? –

+0

첫 번째 예는'fileExistsAtPath'를 사용하여 필요한 디렉토리 구조가 설정되었는지 확인하는 것입니다. 'Documents/myAppFiles/test.txt' 파일을 받으면 행복 할 수도 있습니다. 검사와 저장 작업 사이에 백그라운드 스레드가 올 수 있고 의존하는 디렉토리 구조를 제거하여 파일을 저장하지 못하게 할 수 있습니다. 사과 문서 http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html에서 더 많은 정보가 있습니다. –

1

당신은 그렇지 않습니다. 그러면 레이스가 생길 수 있습니다. 따라서 더 "추한"상태가 될 수 있습니다. codedData의 경우 읽기에 실패하면 nil을 확인하십시오.