デベロッパドキュメントの
Writing an Outline View Data Source
からソースをまんまコピーして実行してみる。
ふぉっふぉっふぉっ、簡単にできるのお。コピペなので全然中身を理解していないため、これをいじくっていくうちに理解を深める・・・予定。(^^;)
次に作りたいな、と思っていたのが「自分用ファイルマネージャ」だったので、このサンプルコードは渡りに船、だった。ラッキー。
一応コードを載せておく。
#import "FileSystemItem.h"
@implementation FileSystemItem
static FileSystemItem *rootItem = nil;
static NSMutableArray *leafNode = nil;
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
+ (void)initialize {
if (self == [FileSystemItem class]) {
leafNode = [[NSMutableArray alloc] init];
}
}
- (id)initWithPath:(NSString *)path parent:(FileSystemItem *)parentItem {
self = [super init];
if (self) {
relativePath = [[path lastPathComponent] copy];
parent = parentItem;
}
return self;
}
+ (FileSystemItem *)rootItem {
if (rootItem == nil) {
rootItem = [[FileSystemItem alloc] initWithPath:@"/" parent:nil];
}
return rootItem;
}
// Creates, caches, and returns the array of children
// Loads children incrementally
- (NSArray *)children {
if (children == nil) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fullPath = [self fullPath];
BOOL isDir, valid;
valid = [fileManager fileExistsAtPath:fullPath isDirectory:&isDir];
if (valid && isDir) {
NSArray *array = [fileManager contentsOfDirectoryAtPath:fullPath error:NULL];
//NSArray *array=[fileManager subpathsAtPath:fullPath];
NSUInteger numChildren, i;
numChildren = [array count];
children = [[NSMutableArray alloc] initWithCapacity:numChildren];
for (i = 0; i < numChildren; i++)
{
BOOL dir,val;
NSString* path=[fullPath stringByAppendingPathComponent:[array objectAtIndex:i]];
val=[fileManager fileExistsAtPath:path isDirectory:&dir];
if(val && dir){
FileSystemItem *newChild = [[FileSystemItem alloc]
initWithPath:[array objectAtIndex:i] parent:self];
[children addObject:newChild];
[newChild release];
}
}
}
else {
children = leafNode;
}
}
return children;
}
- (NSString *)relativePath {
return relativePath;
}
- (NSString *)fullPath {
// If no parent, return our own relative path
if (parent == nil) {
return relativePath;
}
// recurse up the hierarchy, prepending each parent’s path
return [[parent fullPath] stringByAppendingPathComponent:relativePath];
}
- (FileSystemItem *)childAtIndex:(NSUInteger)n {
return [[self children] objectAtIndex:n];
}
- (NSInteger)numberOfChildren {
NSArray *tmp = [self children];
return (tmp == leafNode) ? (-1) : [tmp count];
}
- (void)dealloc {
if (children != leafNode) {
[children release];
}
[relativePath release];
[super dealloc];
}
@end
なお上記のコードは原本に若干手を加えていて、ファイルを全て、ではなくディレクトリだったら表示するようにしている。該当箇所は
BOOL dir,val;
NSString* path=[fullPath stringByAppendingPathComponent:[array objectAtIndex:i]];
val=[fileManager fileExistsAtPath:path isDirectory:&dir];
if(val && dir){
このあたり。

0 件のコメント:
コメントを投稿