开发者

Binding NSPopUpButton to NSArray

开发者 https://www.devze.com 2023-04-09 04:30 出处:网络
I\'m a little lost with bindings on NSPopUpButton. I have a custom class that holds an array of items that I\'d like to display in a pop up. These items are subclasses of NSManagedObjects and they are

I'm a little lost with bindings on NSPopUpButton. I have a custom class that holds an array of items that I'd like to display in a pop up. These items are subclasses of NSManagedObjects and they are contained in an NSArray. I don't want to use an NSArrayController since I've had lots of trouble changi开发者_如何学编程ng the selection programmatically and it feels like cluttering the implementation.

The problem is simply that I don't know how to bind the array properly to the pop up. All I have managed to do is list the array items on the pop up menu, but the titles are core data URIs. I believe I could use the description method to change the title, but this does not sound very advisable.

Any ideas how to bind NSArray to the NSPopUpButton properly?


I think I solved it. I simply created these bindings for NSPopUpButton:

  1. "Content" to the items property (of type NSArray*)

  2. "Selected Object" to selectedItem (of type Item*)

  3. Finally "Content Values" to items.name

For the third binding I implemented valueForKeyPath:

- (id)valueForKeyPath:(NSString *)keyPath
{
    NSArray *components = [keyPath componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];
    if ([components count] == 2 && [components objectAtIndex:0] == @"items")
    {
        return [self.items valueForKey:[components objectAtIndex:1]];
    }
    return [super valueForKeyPath:keyPath];
}

The third binding could've been also a separate array for titles, but I this is much more flexible.

0

精彩评论

暂无评论...
验证码 换一张
取 消