ページ

2010年4月15日木曜日

Application List (2) ファイルパスからアプリ名に変換して表示 - LSCopyDisplayNameForURL

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク

(前回)Cocoaの日々: Application List (1) 雛形作成

前回はドラッグ&ドロップされたファイルパスのファイル名をそのまま表示していた。


アプリケーションの場合、これをファイル名ではなくアプリケーションの名前にしたい。Launch Service API の LSCopyDisplayNameForURL() を使うと取得できる。
Launch Services Reference - LSCopyDisplayNameForURL


前回のサンプルではモデルクラス ApplicationEntry の nameプロパティを(ArrayControllerを介して) NSTableColumn へbindしていた。ここにアプリ名を入れれば bindingsを通じて表示される。

ApplicationEntry.h

@interface ApplicationEntry : NSObject {

NSString* name;
NSString* path;
NSImage* icon;
}
@property (copy) NSString* name;
@property (copy) NSString* path;
@property (retain) NSImage* icon;
@end

path から name を決められる(後日やる iconも同じ)ので pathを引数に取るイニシャライザを追加する。

ApplicationEntry.m

-(id)initWithPath:(NSString*)aPath
{
self = [super init];
if (self != nil) {
self.path = aPath;
NSString* appName;
LSCopyDisplayNameForURL((CFURLRef)[NSURL fileURLWithPath:path], (CFStringRef *)&appName);
if (!appName) {
appName = @"(not found)";
}
self.name = appName;
}
return self;
}


ドロップ処理でこのイニシャライザを使う。
AppListAppDelegate.m

- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info
  row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation
{
NSPasteboard* pboard = [info draggingPasteboard];
NSArray*filenames = [pboard propertyListForType:NSFilenamesPboardType];

for (NSString* filename in filenames) {
ApplicationEntry* entry = [[[ApplicationEntry alloc] initWithPath:filename] autorelease];
[arrayController_ insertObject:entry atArrangedObjectIndex:row];
}

return YES;
}



動かしてみる。
出た。