简体   繁体   中英

Bind custom control to NSArrayController

I've subclassed NSTextField to create a custom control, and I want to bind a property (which is an NSArray ) of my custom control to an NSArrayController . However I don't know how to propagate the array from my control to the NSArrayController . The key-path I'm using on the NSArrayController is arrangedObjects.name . For example, if I'm trying to propagate the array (@"One", @"Two", @"Three") and I simply use:

[boundObject setValue:myArray forKeyPath:@"arrangedObjects.name"]

it will set the value of each element of arrangedObjects.name to the array (@"One", @"Two", @"Three") . What I want to happen is to have the first element in arrangedObjects.name set to @"One" , the second value set to @"Two" , etc.

NSTableColumn does this, so I know it's possible, but I can't figure out how it is implemented.

What's the best way to achieve this?

Ok, well I think I may have answered my own question. I won't mark it as the correct answer right away in case someone can tell me a better way to do this. This way is pretty much a hack.

Anyway, I was reading about NSArrayController here: http://www.cocoadev.com/index.pl?NSArrayController which says:

If valueForKeyPath:@"arrangedObjects.name" is sent to an array controller, one (as expected) gets back an array of name values, but if another object replicates this behaviour, and the table column's value is instead bound to this object, it will display the entire array for each row.

and

You bind the value of an NSTableColumn to arrangedObjects.someKey . If you try to programmatically invoke valueForKeyPath:@"arrangedObjects.someKey" on your array controller, you'll get back the array resulting from invoking valueForKey:@"someKey" on the arrangedObjects array -- this is all fine. So one would think that NSTableColumn 's value can also be bound to my objects someArray.someKey , but this will not work (on several levels).

So basically it sounds like NSTableColumn special cases its bindings for NSArrayController and arrangedObjects which is why it works the right way, and my custom control doesn't.

This doesn't seem very flexible, but it's the only way I can find to make it actually work. I implemented a special case in my bindings for NSArrayController and arrangedObjects and I was able to make it work like I wanted.

A better solution would be much appreciated, though!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM