DotMac

プログラムに関する覚え書き等

Objective-C Memo

Objective-C の自分メモ。


SmartRules

TimeDrawer に、Mail.app の振り分けルールのような「ルール」を実装。現在テスト中。オブジェクトコントローラの使い方とか、正しい(正答)かどうかわからないのですが、とにかくバインディングとNSPredicateで結構簡単にできました。

コンポーネントSmartRules をご自由に利用下さい。

Free download : SmartRules



SmartRules 

smart group, smart folder

FSLogger

http://www.osxbook.com/software/fslogger/


Spotlight ( mdimport )がファイルの更新を監視しているのはこの機構を使用していると思われる。10.5 では一般向けのAPI が実装される模様。

Vector

Vector, Mac用のアプリケーション紹介用サイトとしては既に死んでいます。登録に1ヶ月必要という、なんともな仕様。そんなサイトで、JPO mdimporter がMacビジネス部門第3位でした。多分ダウンロードした人の99%はウインドウズ用のソフトウェアだと思っているはず。

Get kMDItemTextContent Value

You cannot retrieve kMDItemTextContent value from Spotlight query result.

Using these method below, mdimporter plugins can be used as viewer plugins for all the documents that the plugins support.



mdimporterをプラグインとして使用し、kMDItemTextContentの値を取得する



------------ SpotlightTextContentRetriever.h


@interface SpotlightTextContentRetriever : NSObject {


}

+(void)initialize;

+(NSMutableArray* )metaDataOfFileAtPath:(NSString*)targetFilePath;

+(NSString* )textContentOfFileAtPath:(NSString*)targetFilePath;

+(NSMutableDictionary*)executeMDImporterAtPath:(NSString*)mdimportPath forPath:(NSString*)path uti:(NSString*)uti;


@end


------------ SpotlightTextContentRetriever.m

//

//  SpotlightTextContentRetriever.m

//  SpotInside

//

//  Created by Masatoshi Nishikata on 06/11/22.

//  Copyright 2006 __MyCompanyName__. All rights reserved.

//



/*

 Using codes from Apple's BasicPlugin

 ----------------------------------

 Description: Basic CFPlugIn sample code shell, Carbon API

 

 Copyright:  © Copyright 2001 Apple Computer, Inc. All rights reserved.

 

 Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.

 ("Apple") in consideration of your agreement to the following terms, and your

 use, installation, modification or redistribution of this Apple software

 constitutes acceptance of these terms.  If you do not agree with these terms,

 please do not use, install, modify or redistribute this Apple software.

 

 In consideration of your agreement to abide by the following terms, and subject

 to these terms, Apple grants you a personal, non-exclusive license, under Apple’s

 copyrights in this original Apple software (the "Apple Software"), to use,

 reproduce, modify and redistribute the Apple Software, with or without

 modifications, in source and/or binary forms; provided that if you redistribute

 the Apple Software in its entirety and without modifications, you must retain

 this notice and the following text and disclaimers in all such redistributions of

 the Apple Software.  Neither the name, trademarks, service marks or logos of

 Apple Computer, Inc. may be used to endorse or promote products derived from the

 Apple Software without specific prior written permission from Apple.  Except as

 expressly stated in this notice, no other rights or licenses, express or implied,

 are granted by Apple herein, including but not limited to any patent rights that

 may be infringed by your derivative works or by other works in which the Apple

 Software may be incorporated.

 

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO

 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED

 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR

 PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN

 COMBINATION WITH YOUR PRODUCTS.

 

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR

 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE

GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)

 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION

 OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT

 (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN

 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 

 */




#include <Carbon/Carbon.h>

#include <CoreFoundation/CoreFoundation.h>

#include <CoreFoundation/CFPlugInCOM.h>

#import "SpotlightTextContentRetriever.h"



typedef struct PlugInInterfaceStruct {

    IUNKNOWN_C_GUTS;

Boolean (*GetMetadataForFile)(void* myInstance, 

  CFMutableDictionaryRef attributes, 

  CFStringRef contentTypeUTI,

  CFStringRef pathToFile);

} MDImporterInterfaceStruct;



static MDImporterInterfaceStruct **mdimporterInterface = NULL;


/*

typedef Boolean (*getMetadataForFileFunction)(void* thisInterface, 

  CFMutableDictionaryRef attributes, 

  CFStringRef contentTypeUTI,

  CFStringRef pathToFile);


*/



@implementation SpotlightTextContentRetriever


static NSArray* mdimporterArray;


+(void)initialize

{

// Get and store MDImporter list

NSTask *task = [[NSTask alloc] init];

NSPipe *messagePipe = [NSPipe pipe];

[task setLaunchPath:@"/usr/bin/mdimport"];

[task setArguments:[NSArray arrayWithObjects: @"-L" ,nil]];


[task setStandardError : messagePipe];

[task launch];

[task waitUntilExit];


NSData *messageData = [[messagePipe fileHandleForReading] availableData]; 


NSString* message;

message = [[[NSString alloc] initWithData:messageData

encoding:NSUTF8StringEncoding] autorelease];

[task release];

// Cut unwanted string

NSRange firstReturn = [message rangeOfString:@"¥n"];

NSString* arrayStr = [message substringFromIndex:  firstReturn.location-1];

// Convert string to array

mdimporterArray =   [[arrayStr propertyList] retain];

/*

// Convert percentage encoded string

int hoge;

NSMutableArray* array = [NSMutableArray array];

for( hoge = 0; hoge < [tempArray count]; hoge++ )

{

NSString* aPath = [tempArray objectAtIndex:hoge];

aPath = [aPath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];


[array addObject:aPath ];

}

mdimporterArray = [[NSArray arrayWithArray: array ] retain];

*/

//NSLog(@"mdimporterArray %@", [mdimporterArray description]);

}


+(NSMutableArray* )metaDataOfFileAtPath:(NSString*)targetFilePath

{

// Get UTI of the given file

targetFilePath = [targetFilePath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

NSURL* anUrl = [NSURL URLWithString: targetFilePath];

FSRef ref;

CFURLGetFSRef(anUrl,&ref);

CFTypeRef outValue;

LSCopyItemAttribute (

&ref,

kLSRolesAll,

kLSItemContentType,

&outValue

);

if( outValue == nil ) return nil;

NSString* uti = [NSString stringWithString:outValue];

CFRelease(outValue);

//NSLog(@"uti %@",uti);

//----------------

//Get handlers that can handle the file

CFArrayRef ha = LSCopyAllRoleHandlersForContentType (

uti,

kLSRolesAll

);

NSArray* handlerArray = [NSArray arrayWithArray: ha];

CFRelease(ha);

//NSLog(@"handlers %@",[handlerArray description]);

//----------------

//Evaluate

int hoge;

for( hoge = 0; hoge < [mdimporterArray count]; hoge++ )

{

NSString* mdimporterPath = [mdimporterArray objectAtIndex:hoge];

NSBundle* bndl = [NSBundle bundleWithPath: mdimporterPath ];

if( bndl != nil )

{

int piyo;

for( piyo = 0; piyo < [handlerArray count]; piyo++ )

{

NSString* aHandler = [handlerArray objectAtIndex:piyo];

//NSLog(@"Compareing %@, %@ ",aHandler, [bndl bundleIdentifier]);

if( [aHandler isEqualToString:[bndl bundleIdentifier] ] )

{

//NSLog(@"Executing mdimporterPath %@ for targetFilePath %@",mdimporterPath,targetFilePath);

// found one mdimporter

NSMutableDictionary* attributes = 

[SpotlightTextContentRetriever executeMDImporterAtPath:mdimporterPath 

  forPath:targetFilePath

  uti:uti];

if( [attributes objectForKey:kMDItemTextContent] != nil )

return attributes;


}

}

}else

{

//NSLog(@"bndl is null");

}

}

/*

// use text mdimporter if appropriate importer cannot be found

///System/Library/Spotlight/RichText.mdimporter

//NSLog(@"%@",uti);

NSMutableDictionary* attributes = 

[SpotlightTextContentRetriever executeMDImporterAtPath:@"/System/Library/Spotlight/RichText.mdimporter" 

  forPath:targetFilePath

  uti:uti];

 

return attributes;

*/

return nil;

}


+(NSString* )textContentOfFileAtPath:(NSString*)targetFilePath

{

NSMutableDictionary* attributes = 

[SpotlightTextContentRetriever metaDataOfFileAtPath:targetFilePath];

id textContent = [attributes objectForKey:kMDItemTextContent];

if( [textContent isKindOfClass:[NSString class]]  )

{

//NSLog(@"%@",textContent);

return textContent;

}

return nil;

}



+(NSMutableDictionary*)executeMDImporterAtPath:(NSString*)mdimportPath forPath:(NSString*)path uti:(NSString*)uti

{

mdimportPath = [mdimportPath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

NSMutableDictionary* attributes = nil;

CFBundleRef bundle;


CFURLRef url = CFURLCreateWithString (

nil,

mdimportPath,

nil

);

 

if( url == nil ) return nil;


/*  

NSLog(@"start executeMDImporterAtPath");


NSLog(@"Execute GetMetadataForFile");

NSLog(@"uti %@",uti);

NSLog(@"path %@",path);

NSLog(@"mdimport %@",mdimportPath );

*/

// Create CFPlugInRef

CFPlugInRef plugin = CFPlugInCreate(NULL, url);

CFRelease(url);


if (!plugin)

{

//NSLog(@"Could not create CFPluginRef.¥n");

return nil;

}


//  The plug-in was located. Now locate the interface.


BOOL foundInterface = NO;

CFArrayRef factories;

//  See if this plug-in implements the Test type.

factories = CFPlugInFindFactoriesForPlugInTypeInPlugIn( kMDImporterTypeID, plugin );

//  If there are factories for the Test type, attempt to get the IUnknown interface.

if ( factories != NULL )

{

CFIndex factoryCount;

CFIndex index;

factoryCount = CFArrayGetCount( factories );

if ( factoryCount > 0 )

{

for ( index = 0 ; (index < factoryCount) && (foundInterface == false) ; index++ )

{

CFUUIDRef factoryID;

//  Get the factory ID for the first location in the array of IDs.

factoryID = (CFUUIDRef) CFArrayGetValueAtIndex( factories, index );

if ( factoryID )

{

IUnknownVTbl **iunknown;

//  Use the factory ID to get an IUnknown interface. Here the plug-in code is loaded.

iunknown = (IUnknownVTbl **) CFPlugInInstanceCreate( NULL, factoryID, kMDImporterTypeID );

if ( iunknown )

{

//  If this is an IUnknown interface, query for the test interface.

(*iunknown)->QueryInterface( iunknown, CFUUIDGetUUIDBytes( kMDImporterInterfaceID ), (LPVOID *)( &mdimporterInterface ) );

// Now we are done with IUnknown

(*iunknown)->Release( iunknown );

if ( mdimporterInterface )

{

// We found the interface we need

foundInterface = true;

}

}

}

}

}

}

CFRelease( factories );


if ( foundInterface == false )

{

}

else

{

attributes = [NSMutableDictionary dictionary];

path = [path stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

//NSLog(@"start getMetadataForFile CFPlugin");

(*mdimporterInterface)->GetMetadataForFile( mdimporterInterface, 

attributes, 

uti,

path);

//NSLog(@"%@",[attributes description]);


(*mdimporterInterface)->Release( mdimporterInterface );


}

// Finished


CFRelease( plugin );

plugin = NULL;

return attributes;

}


@end


 

GetCurrentKeyModifiers( )修飾キーの押され具合をチェック

#import <HIToolbox/CarbonEventsCore.h> // with carbon framework

 

int modKey = GetCurrentKeyModifiers( );


alphaLock 0x400

controlKey 0x1000

optionKey 0x800

shiftKey 0x200

cmdKey 0x100

 

Play System Sound (SystemSoundPlay)

eg.

SystemSoundPlay(0);



0:Screen capture sound

1:Completion file movement sound

2:Reversed sound of number 1?

3:Volume control sound

4:Something collapsing sound??

5:Heavy switching sound

6:Switching sound 

7:Switching sound 2

8:Switching sound 3

9:Dragging noise

10:Dragging noise 2

11:Heavy click sound

12:Similar to 7 but shorter??

13:Empty Trash sound

14:Throwing away ??

15:Dock item poof sound

16:Move to trash 

17:Click sound

18-21: Sweeping ??

22-23: Complete Burning Disk

24: Clicking inactive window beep


 

Get mouse button status マウスボタンの状態をチェックする

#import <HIToolbox/CarbonEventsCore.h>


BOOL flag = GetCurrentButtonState();



 

GengoCalendarDate

「平成18年1月1日」という元号日付をNSStringをNSDateに変える

メソッドです。(別にNSCalendarDateのエクステンションでなくても構いません





これらを使用しています


正規表現

AGRegex


全角半角変換

http://blogs.dion.ne.jp/fujidana/

但し、変換不可能なキャラクタをそのまま返すように

#pragma mark other characters

} else {

//if (passFwMask & FWHWOtherMask || passHwMask & FWHWOtherMask) {

newChar[j--] = c;

//}

}

としました。






#import <Cocoa/Cocoa.h>


@interface NSCalendarDate (GengoCalendarDate)


+(NSDate*)dateWithGengouString:(NSString*)gengou;

@end




--------------------------------------------------------

//

//  GengoCalendarDate.m

//  GengoCalendarDate エンコードはMacOS日本語にしてください




#import "GengoCalendarDate.h"

#import "NSString_FullwidthHalfwidth.h"

#import "AGRegex.h"



@implementation NSCalendarDate (GengoCalendarDate)


- (int)yearOfHeisei //2000 = 12

{

int year = [super yearOfCommonEra];

return (year -= 1988);//

}


+(NSDate*)dateWithGengouString:(NSString*)gengou // heisei and showa

{

AGRegex* chomp = [AGRegex regexWithPattern:[NSString stringWithCString:"¥n| | "]];

AGRegex* heisei = [AGRegex regexWithPattern:[NSString stringWithCString:"(?<=平成)[0-9]+(?=年)|(?<=平)[0-9]+(?=年)"]];

AGRegex* showa = [AGRegex regexWithPattern:[NSString stringWithCString:"(?<=昭和)[0-9]+(?=年)|(?<=昭)[0-9]+(?=年)"]];

AGRegex* tsuki = [AGRegex regexWithPattern:[NSString stringWithCString:"[0-9]+(?=月)"]];

AGRegex* nichi = [AGRegex regexWithPattern:[NSString stringWithCString:"[0-9]+(?=日)"]];

AGRegexMatch* match;

int nen_int, tsuki_int, nichi_int;

///

NSString* str = [chomp replaceWithString:@"" inString:gengou];

str = [str halfwidthString];

match = [heisei findInString:str];

if( match != nil )

{

nen_int  = [[str substringWithRange: [match range] ] intValue] + 1988;

}else

{

match = [showa findInString:str];

if( match != nil )

{

nen_int  = [[str substringWithRange: [match range] ] intValue] + 1925;

}

}

match = [tsuki findInString:str];

if( match != nil )

tsuki_int = [[str substringWithRange: [match range] ] intValue];

match = [nichi findInString:str];

if( match != nil )

nichi_int = [[str substringWithRange: [match range] ] intValue];

NSString* format = [NSString stringWithFormat:@"%d,%d,%d",nen_int ,tsuki_int, nichi_int];

NSCalendarDate* calenderDate = [NSCalendarDate 

    dateWithString: format 

    calendarFormat:@"%Y,%m,%d"];

//NSLog(@"%@",[calenderDate descriptionWithCalendarFormat:@"%y/%B/%d/%A"]);

return (NSDate*)calenderDate;

}


@end


 

NSMetadataQuery

NSMetadataQuery seems to have bugs and unable to get NSMetadataQueryResultContentRelevanceAttribute value.


Use MDQueryRef instead.




#import <Cocoa/Cocoa.h>


@interface MyDocument : NSDocument

{

    IBOutlet id field;

MDQueryRef _query;

}

- (IBAction)search:(id)sender;

@end


---------


#import "MyDocument.h"



@implementation MyDocument


- (id)init

{

    self = [super init];

    if (self) {

     }

    return self;

}


- (NSString *)windowNibName

{

    return @"MyDocument";

}


- (void)windowControllerDidLoadNib:(NSWindowController *) aController

{

    [super windowControllerDidLoadNib:aController];

 

}



- (IBAction)search:(id)sender

{

if( [[field stringValue] isEqualToString:@"" ] ) return;

        NSString *predicateFormat = @"(kMDItemTextContent == \"?%@*\"c) && (kMDItemContentType != 'com.apple.mail.emlx') && (kMDItemContentType != 'public.vcard')";

_query = MDQueryCreate (

  NULL,

[NSString stringWithFormat:predicateFormat,[field stringValue]],

  [NSArray arrayWithObjects:kMDQueryResultContentRelevance,

  kMDItemPath, kMDItemDisplayName, kMDItemFSName,nil ],

  [NSArray arrayWithObject:kMDQueryResultContentRelevance]

  );

MDQuerySetSearchScope (

  _query,

  [NSArray arrayWithObject:kMDQueryScopeComputer ],

  0

  );


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finish) name:kMDQueryDidFinishNotification object:_query];



MDQueryExecute (

_query,

kMDQuerySynchronous

);



}



-(void)finish

{


[[NSNotificationCenter defaultCenter] removeObserver:self

name:nil

  object:_query];

MDItemRef miref;

CFIndex idx;

idx = MDQueryGetResultCount(_query);


CFIndex hoge;

for( hoge = 0; hoge < idx; hoge++ )

{

miref = MDQueryGetResultAtIndex( _query, hoge);


NSString* name = (NSString*)MDItemCopyAttribute (

miref,

kMDItemFSName

);

NSString* path = (NSString*)MDItemCopyAttribute (

miref,

kMDItemPath

);

NSString* displayname = (NSString*)MDItemCopyAttribute (

miref,

kMDItemDisplayName

);

NSNumber* score = (NSNumber*)MDQueryGetAttributeValueOfResultAtIndex (

  _query,

  kMDQueryResultContentRelevance,

  hoge

  );

if( score != nil )

NSLog(@"score %f",[score floatValue]);

}

}


@end



 

Create Zip file from data which user can unarchive

/*



When you want to save your document as a Zip file.


using

cocoadev.com

http://www.cocoadev.com/index.pl?UsingZipFilesExamples



Please change the scratch folder etc to appropriate ones.


*/



-(void)usageExample

{

// create sample data

NSString* text = @"test";

NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];

// Zip test 1

/*

NSData* convertedData = [self zip:data];

[convertedData writeToFile:[NSHomeDirectory() stringByAppendingPathComponent: @"Desktop/zip result"] atomically:YES];


*/

// Zip test 2

NSFileWrapper* zipwrap = [[[NSFileWrapper alloc] initDirectoryWithFileWrappers:NULL ] autorelease];

[zipwrap addRegularFileWithContents:data   preferredFilename:@"data1" ];

[zipwrap addRegularFileWithContents:data   preferredFilename:@"data2" ];


NSData* convertedData = [self zip:zipwrap];

[convertedData writeToFile:[NSHomeDirectory() stringByAppendingPathComponent: @"Desktop/zip result"] atomically:YES];


// Unzip

NSFileWrapper* wrapper = [self unzip:convertedData];

if( [wrapper isRegularFile] )

{

NSLog(@"this is a regular file wrapper");

}

else

{

NSLog(@"this is a directory wrapper");


NSDictionary* regularFileWrappers = [wrapper fileWrappers];

NSLog(@"contains %@", [[regularFileWrappers allKeys] description] );

}

[wrapper  writeToFile:[NSHomeDirectory() stringByAppendingPathComponent: @"Desktop/unzip result"] atomically:YES updateFilenames:YES];


}




-(NSData*)zip:(id)raw //raw must be NSData or NSFileWrapper

{

NSString* scratchFolder =[NSHomeDirectory() stringByAppendingPathComponent: @"Desktop/"];

NSString* sourceFilename = @"data";

NSString* targetFilename = @"zipped data";

NSString* sourcePath =[scratchFolder stringByAppendingPathComponent: sourceFilename];

NSString* targetPath =[scratchFolder stringByAppendingPathComponent: targetFilename];

BOOL flag = NO;

if( [raw isKindOfClass:[NSData class]] )

flag = [raw writeToFile:sourcePath atomically:YES];

else if( [raw isKindOfClass:[NSFileWrapper class]] )

flag = [raw writeToFile:sourcePath atomically:YES updateFilenames:YES];

if( flag == NO )

{

NSLog(@"Fail to write.");

return NULL;

}


/* Assumes sourcePath and targetPath are both

valid, standardized paths. */

//----------------

// Create the zip task

NSTask * backupTask = [[NSTask alloc] init];

[backupTask setLaunchPath:@"/usr/bin/ditto"];

[backupTask setArguments:

[NSArray arrayWithObjects:@"-c", @"-k", @"-X", @"--rsrc"

sourcePath, targetPath, nil]];

// Launch it and wait for execution

[backupTask launch];

[backupTask waitUntilExit];

// Handle the task's termination status

if ([backupTask terminationStatus] != 0)

{

NSLog(@"Sorry, didn't work.");

return NULL;

}

// You *did* remember to wash behind your ears ...

// ... right?

[backupTask release];

NSData* convertedData = [[[NSData alloc] initWithContentsOfFile:targetPath] autorelease];

//delete scratch

[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceDestroyOperation

source:scratchFolder

destination:@"" 

  files:[NSArray arrayWithObjects:sourceFilename, targetFilename,NULL]

tag:NULL];

return convertedData;

}



-(NSFileWrapper*)unzip:(NSData*)zipData

{

NSString* scratchFolder =[NSHomeDirectory() 

stringByAppendingPathComponent: @"Desktop/"];

NSString* sourceFilename = @"zipped data";

NSString* targetFilename = @"unzipped folder";

NSString* sourcePath =[scratchFolder stringByAppendingPathComponent: sourceFilename];

NSString* targetPath =[scratchFolder stringByAppendingPathComponent: targetFilename];

BOOL flag = [zipData writeToFile:sourcePath atomically:YES];

if( flag == NO )

{

NSLog(@"error");

return NULL;

}

//Unzip

//-------------------

NSTask *cmnd=[[NSTask alloc] init];

[cmnd setLaunchPath:@"/usr/bin/ditto"];

[cmnd setArguments:[NSArray arrayWithObjects:

@"-v",@"-x",@"-k",@"--rsrc",sourcePath,targetPath,nil]];

[cmnd launch];

[cmnd waitUntilExit];

// Handle the task's termination status

if ([cmnd terminationStatus] != 0)

{

NSLog(@"Sorry, didn't work.");

return NULL;

}

// You *did* remember to wash behind your ears ...

// ... right?

[cmnd release];

//unzip

//

NSArray* contents = [[NSFileManager defaultManager] directoryContentsAtPath:targetPath];

NSFileWrapper* wrapper;

if( [contents count] == 1 )

{

NSString* onepath;

onepath = [targetPath stringByAppendingPathComponent:[contents lastObject]];

NSData* data = [NSData dataWithContentsOfFile:onepath];


wrapper = [[[NSFileWrapper alloc] initRegularFileWithContents:data  ] autorelease];


}

else if( [contents count] > 1 )

{

wrapper = [[[NSFileWrapper alloc] initDirectoryWithFileWrappers:NULL ] autorelease];

unsigned hoge;

for( hoge = 0; hoge < [contents count]; hoge++ )

{

NSString* onepath;

NSString* onefilename;

onefilename = [contents objectAtIndex:hoge];

onepath = [targetPath stringByAppendingPathComponent:onefilename];


NSData* data = [NSData dataWithContentsOfFile:onepath];

[wrapper addRegularFileWithContents:data   preferredFilename:onefilename ];

}

}

//delete scratch

[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceDestroyOperation

source:scratchFolder

destination:@"" 

  files:[NSArray arrayWithObjects:sourceFilename, targetFilename,NULL]

tag:NULL];

return wrapper;

}


 

Parting Words (著作権, 連絡先情報, etc.)