Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Bindings won't work Xcode 6 Beta 5

I'm doing a simple test program using bindings in Swift on OSX. Having an NSTableView, NSArrayController and a model class I try to hook them up together, but without success! The build compiles but gives instantly this error: Thread 1: EXC_BAD_ACCESS(code=1, address = 0x0)

Code looks like this:
model class:

import Foundation

class Name {
   var firstName = "Brook"
   var lastName = "Brooklyn"
}

view controller:

import Cocoa

class ViewController: NSViewController {

    dynamic var names = [Name]()  // serves as the content for Array-Controller
                        
    override func viewDidLoad() {
        super.viewDidLoad()

        // populate array
        var name1 = Name()
        var name2 = Name()
    
        names.append(name1)
        names.append(name2)
                                
}

override var representedObject: AnyObject? {
    didSet {
    // Update the view, if already loaded.
    }
                                
}

}

I've setup the array controller to use my class "Name" and added the keys "firstName" and "lastName"

Here's the storyboard:

StoryboardBindings1Bindings2

Has anyone already had any success setting up bindings on Xcode 6 Beta 5? Any help is appreciated!

Thanks!

EDIT: As suggested I tried adding the "dynamic" keyword to the property to enable bindings, but it gives the same error and doesn't work.
I've also tried subclassing the "Name" class from NSObject in order to use the old Objective-C support from Cocoa, but bindings still don't work!

like image 830
Nairam Avatar asked Aug 12 '14 16:08

Nairam


3 Answers

Beta 5 requires you to explicitly set your properties as dynamic in order for KVO/bindings to work:

dynamic var firstName = "Brook"

See the Dynamic declaration modifier section of the release notes for more information.

The dynamic keyword enables KVO, proxying, and other advanced Cocoa features to work reliably with Swift declarations.

like image 173
Pascal Bourque Avatar answered Nov 08 '22 14:11

Pascal Bourque


You have to select the Table View Cell and bind it's value to Table Cell View with the appropriate objectValue. I don't know how to get rid of the exclamation-mark / warning, but it works.

enter image description here

like image 20
Fabian Zeindl Avatar answered Nov 08 '22 14:11

Fabian Zeindl


Are you using NSCell or NSView based tables? How you set up bindings is different for these. What you are doing looks correct for NSCell based tables.

When I set up a NSTableView today, it was a NSView based table, so I had to select the TextField and bind to "Table Cell View" with a Model Key Path "objectValue.name"

See the Table View Programming Guide for Mac: Populating a Table View Using Cocoa Bindings documentation

like image 2
Matt Connolly Avatar answered Nov 08 '22 15:11

Matt Connolly