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