クラシックアプリケーションのファイルを読み込む


CodeWarrior で作成したオリジナルアプリケーションのファイルを Cocoa で読み込む方法です。

ここに紹介する方法はあくまでも私が試行錯誤の末に作成した「回答例」のうちの一つであり、「模範解答」ではないことをご了承ください。

まず、 - (BOOL)readFromFile:(NSString *)fileName ofType:(NSString *)docType をオーバーライドして、ファイルパスを控えておきます。

- (BOOL)readFromFile:(NSString *)fileName ofType:(NSString *)docType
{
MyFilePath = fileName;
return [super readFromFile:fileName ofType:docType];
}

次に - (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType の中で”書類のタイプ”を調べます。

- (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType
{
[aMyData release];
if ([aType isEqualToString:@"ABCD"]) // Cocoa のファイルなら通常通り読み込む
aMyData = [[NSUnarchiver unarchiveObjectWithData:data] retain];
else
{ // Cocoa のファイルではない、クラシックアプリケーションのファイルなら以下のようにします。
aMyData = [[MyData alloc] init];
[aMyData initWithOldFile:MyFilePath]; // 本当は "NO" が返ってきたら何かしなければなりません。
}

return YES;
}

プロジェクトにCarbon.framework を取り込んでおき、aMyData を定義するクラスの中でクラシックアプリケーションのファイルを読み込みます。

- (BOOL)initWithOldFile:(NSString *)path
{
short aRef;
long aBufferSize = ****; // 読み込むデータの大きさ
FInfo aInfo;
FSSpec aSfFile;
FSRef targetFileFSRef;
OSErr result;

if (self = [super init])
{
if (![path getFSRef:&targetFileFSRef createFileIfNecessary:NO])
return NO;

result = FSGetCatalogInfo( &targetFileFSRef, kFSCatInfoNone, NULL, NULL, &aSfFile, NULL );
if (result != noErr)
return NO;

result = FSpGetFInfo(&aSfFile, &aInfo);
if (result != noErr)
return NO;

if ( aInfo.fdType == 'EFGH')
{ // ファイルタイプを確認
if ( noErr == FSpOpenDF(&aSfFile, fsRdPerm, &aRef))
{
FSRead( aRef, &aBufferSize, &aBuffer );
// aBufferSize からデータを読み込む
}
} // ファイルタイプを確認
} // self = [super init]
return YES;
}