Реализация NSOutlineViewDataSource с использованием MonoMac

Я пытаюсь реализовать источник данных для NSOutlineView. Проблема в том, что я не знаю, какой тип объекта нужно вернуть из outlineView:child:ofItem:.

Текущий код выглядит так:

[Export("outlineView:child:ofItem:")]
public NSObject childOfItem(NSOutlineView outline, int child, NSObject item)
{
    return new MyItem();
}

С MyItem:

public class MyItem : NSObject
{}

EDIT: С этим кодом я получаю InvalidCastException сразу после возврата MyItem.


person Sander Rijken    schedule 12.01.2012    source источник


Ответы (2)


Если вы наследуете новый тип от NSOutlineViewDataSource, вам не следует повторно экспортировать его селектор outlineView:child:ofItem: в собственный метод. Вместо этого вам следует переопределить метод GetChild, который уже экспортирует этот селектор, например.

public overrride NSObject GetChild (NSOutlineView outlineView, int childIndex, NSObject ofItem)
{
    return new MyItem ();
}

Примечание: это может не помочь, так как я не пробовал (в основном я использую MonoTouch), но просматриваю другие селекторы, которые вы можете переопределить/экспортировать в своем приложении (чтобы узнать, не следует ли вам переопределить- из базового класса, от которого вы наследуете).

person poupou    schedule 22.01.2012
comment
Большое спасибо, это было решение - person Sander Rijken; 30.01.2012

Рассматривали ли вы возможность использования NSTreeController? Это помогает управлять представлением схемы для вас и очень удобно. NSTreeController использует класс с именем NSTreeNode для представления узлов в представлении структуры, и каждый NSTreeNode имеет метод representedObject, позволяющий получить доступ к объекту модели.

В любом случае, если вы не хотите использовать NSTreeController или NSTreeNode, вы можете просто напрямую вернуть объект модели. Вот несколько примеров кода Objective-C из руководств Apple.

@implementation DataSource
// Data Source methods

- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {

    return (item == nil) ? 1 : [item numberOfChildren];
}


- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
    return (item == nil) ? YES : ([item numberOfChildren] != -1);
}


- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {

    return (item == nil) ? [FileSystemItem rootItem] : [(FileSystemItem *)item childAtIndex:index];
}


- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
    return (item == nil) ? @"/" : [item relativePath];
}

@end


@interface FileSystemItem : NSObject
{
    NSString *relativePath;
    FileSystemItem *parent;
    NSMutableArray *children;
}

+ (FileSystemItem *)rootItem;
- (NSInteger)numberOfChildren;// Returns -1 for leaf nodes
- (FileSystemItem *)childAtIndex:(NSUInteger)n; // Invalid to call on leaf nodes
- (NSString *)fullPath;
- (NSString *)relativePath;

@end


@implementation FileSystemItem

static FileSystemItem *rootItem = nil;
static NSMutableArray *leafNode = nil;

+ (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];

            NSUInteger numChildren, i;

            numChildren = [array count];
            children = [[NSMutableArray alloc] initWithCapacity:numChildren];

            for (i = 0; i < numChildren; i++)
            {
                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

Это не MonoMac, но должна быть та же идея.

person Tony    schedule 15.01.2012
comment
Я понимаю, что вы говорите, вы также говорите, что я могу напрямую вернуть свой объект модели. Когда я это делаю, я получаю InvalidCastException, поэтому я думаю, что это проблема, специфичная для MonoMac. Я попробую предложение TreeController, но не думаю, что это поможет. - person Sander Rijken; 17.01.2012