Reload a NSWindow Xcode Swift2 - swift

I'm working on an NSOutlineView that uses NSView subclasses to generate custom cells in the outline. This I've gotten to work, BUT after the Outline sucks in the data from the model class and displays it correctly, the Outline is released(?) from memory / goes to nil and I haven't figured out a way to get it back.
Here is the MainViewController class
class MainWindowController: NSWindowController, ShareInfoDelegate, NSOutlineViewDelegate, NSOutlineViewDataSource {
override var windowNibName: String {
return "MainWindowController"
}
#IBOutlet var daOutline: NSOutlineView!
// The NSoutline I'm trying to get back to
Some stuff related to the test data (Omitted)
leading us to the NSOutlineViewDataSource stuff
//MARK: - NSOutlineViewDataSource
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
if let item: AnyObject = item {
switch item {
case let work as Work:
return work.movements[index]
case let movement as Movement:
return movement.tracks[index]
default:
let track = item as! Track
return track.credits[index]
}
} else {
if allWorks.count > 0 {
return allWorks[index]
}
}
let q = "patience"
return q
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
switch item {
case let work as Work:
return (work.movements.count > 0) ? true : false
case let movement as Movement:
return (movement.tracks.count > 0) ? true : false
case let track as Track:
return (track.credits.count > 0) ? true: false
default:
return false
}
}
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
if let item: AnyObject = item {
switch item {
case let work as Work:
return work.movements.count
case let movement as Movement:
return movement.tracks.count
case let track as Track:
return track.credits.count
default:
return 0
}
} else {
return allWorks.count
}
}
func outlineView(daOutline: NSOutlineView, viewForTableColumn theColumn: NSTableColumn?, item: AnyObject) -> NSView? {
switch item {
case let worked as Work:
let cell = daOutline.makeViewWithIdentifier("newTry", owner:self) as! newTry
cell.fourthLabel.stringValue = worked.composer
cell.fourthCell.stringValue = worked.title
return cell
case let moved as Movement:
let cell2 = daOutline.makeViewWithIdentifier("SecondTry", owner:self) as! SecondTry
cell2.roman.stringValue = moved.name!
cell2.details.stringValue = moved.sections!
cell2.track.stringValue = "0"
return cell2
default:
print("probably not")
}
print("not again")
return nil
}
func outlineView(daOutline: NSOutlineView, heightOfRowByItem item: AnyObject) -> CGFloat {
switch item {
case let worked as Work:
return 40
default:
return 24
}
}
And the stuff in WindowDidLoad
override func windowDidLoad() {
super.windowDidLoad()
let nib = NSNib(nibNamed: "newTry", bundle: NSBundle.mainBundle())
daOutline.registerNib(nib!, forIdentifier: "newTry")
let nib2 = NSNib(nibNamed: "SecondTry", bundle: NSBundle.mainBundle())
daOutline.registerNib(nib2!, forIdentifier: "SecondTry")
//give Sender it's Receiver
mailItOut.delegate = receiver
allWorks.append(work1)
allWorks.append(work2)
work1.movements.append(move1)
work1.movements.append(move2)
work1.movements.append(move3)
work1.movements.append(move4)
work2.movements.append(move5)
work2.movements.append(move6)
work2.movements.append(move7)
daOutline.reloadData()
daOutline?.expandItem(work1, expandChildren: false)
daOutline?.expandItem(work2, expandChildren: false)
}
}
And Finally what the newTry NSView class looks like
class newTry: NSView {
var delegate: ShareInfoDelegate?
#IBOutlet weak var fourthCell: NSTextField!
#IBOutlet weak var fourthLabel: NSTextField!
#IBAction func cellAdd(sender: NSTextField) {
var catchIt: String = String()
catchIt = sender.stringValue
if catchIt != "" {
tryAgain = catchIt
whichField = "title"
//Trigger the sender to send message to it's Receiver
mailItOut.sendMessage()
}
}
The cellAdd Action is used to try and get user input from the text cells back into the model. To do this I (AFAIK) need to access the NSOutline (daOutline) and get which row I'm at and put the data from the sender into the appropriate part of the Model class. Which is something that I've managed to get to work in a standard (1 cell / 1 data value) outline. But in this prototype, as far as I can tell, the MainWindowController has released all of its contents and daOutline is nil (bad).
How do I get XCode to bring / reload the completed outline (or never release it) and get daOutline to a non nil state?

For those who come after there appeared to be two problems that led to the NSOutline outlet becoming nil. The first one was that in implementing the delegate protocol "shareInfoDelegate" I was creating a new instance of the MainWindowController, not the one with the data in it. This new instance did NOT have the IBOutlets connected (or much of anything useful about it).
Once I scrapped the Delegate and moved to using NSNotification to update information about the NSView textFields my NSOutline came "back".
The second, more minor, problem was that in the NSView nib file I placed and NSBox to mimic the behavior of a group row (e.g. a gray background). As a side effect the NSBox was inhibiting the normal row select behavior of the outline. Which made it very hard to determine which row was selected. When I deleted the NSBox, row selection became much more easy to determine.
in particular this Question and the answer by Chuck were helpful in sniffing this out.
Why is my NSOutlineView datasource nil?
Thanks Indeed(!)

Related

Why View-Based NSOutlineView with autosaveExpandedItems true ignores expanded upon reloadData?

I use a NSOutlineView that auto saves expanded state. If I manually reload data when dataSource updates, the func outlineView(_ outlineView: NSOutlineView, itemForPersistentObject object: Any) -> Any? datasource method is not called anymore and every cell collapses. Any idea why this might happen?
Tried to reloadItem with nil send as param but still no good.
I use this for persisting expanded rows:
func outlineView(_ outlineView: NSOutlineView, persistentObjectForItem item: Any?) -> Any? {
return NSKeyedArchiver.archivedData(withRootObject: item)
}
func outlineView(_ outlineView: NSOutlineView, itemForPersistentObject object: Any) -> Any? {
guard let data = object as? Data,
let item = NSKeyedUnarchiver.unarchiveObject(with: data) as? Category else { return nil }
let foundItem = recursiveSearch(for: item, in: viewModel.dataSource.value)
return foundItem
}
And this to reloadData:
viewModel.dataSource.subscribe(onNext: { [weak self] _ in
self?.outlineView.reloadData()
}).disposed(by: disposeBag)
IMHO autosaving is sort of half-baked feature and it doesn't work as expected. In other words, it's implemented in a way that it restores the state when your application launches (just once) and then you're on your own.
Implement your own one utilizing outlineViewItemDidExpand(_:) & outlineViewItemDidCollapse(_:) (especially when we're reloading, ...).
Couple of tricks you can use if you do not want to implement custom autosaving. But I wouldn't rely on them.
First trick - tell the NSOutlineView to reload persistent state
NSOutlineView inherits from the NSTableView and the autosaveName property documentation says:
If you change the value of this property to a new name, the table reads in any saved information and sets the order and width of this table view’s columns to match. Setting the name to nil removes any previously stored state from the user defaults.
What is inaccurate here - setting it to nil doesn't remove previously stored expanded items state for NSOutlineView. We can use it to force the NSOutlineView to reload expanded items state:
class ViewController: NSViewController, NSOutlineViewDelegate, NSOutlineViewDataSource {
#IBOutlet var outlineView: NSOutlineView!
// It's for testing, to demonstrate the persistent state reloading
private var doNotLoad = true
override func viewDidAppear() {
super.viewDidAppear()
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.doNotLoad = false
let autosaveName = self.outlineView.autosaveName
self.outlineView.autosaveName = nil
self.outlineView.reloadData()
self.outlineView.autosaveName = autosaveName
}
}
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if (doNotLoad) {
return 0
}
return item == nil ? data.count : (item as! Node).children.count
}
}
If you'd like to comply with the documentation, do not use nil and set some fake name. But I would expect that once the bug is fixed, the persistent state will be removed if we change the autosaveName or if we set it set to nil.
Second trick - load & expand yourself
Imagine you have the following Node class:
class Node {
let id: Int
let children: [Node]
// ...
}
And your data source implements:
func outlineView(_ outlineView: NSOutlineView, persistentObjectForItem item: Any?) -> Any? {
(item as! Node).id
}
func outlineView(_ outlineView: NSOutlineView, itemForPersistentObject object: Any) -> Any? {
guard let id = object as? Int else { return nil }
return data.firstNode { $0.id == id }
}
The firstNode is not related to this question, but here's the implementation (because it's mentioned in the code):
extension Array where Self.Element == Node {
// Search for a node (recursively) until a matching element is found
func firstNode(where predicate: (Element) throws -> Bool) rethrows -> Element? {
for element in self {
if try predicate(element) {
return element
}
if let matched = try element.children.firstNode(where: predicate) {
return matched
}
}
return nil
}
}
Then you can reloadData & expand all the items by yourself:
outlineView.reloadData()
if outlineView.autosaveExpandedItems,
let autosaveName = outlineView.autosaveName,
let persistentObjects = UserDefaults.standard.array(forKey: "NSOutlineView Items \(autosaveName)"),
let itemIds = persistentObjects as? [Int] {
itemIds.forEach {
let item = outlineView.dataSource?.outlineView?(self.outlineView, itemForPersistentObject: $0)
self.outlineView.expandItem(item)
}
}

Next object instance IGListKit

Edit: I am new to the field, I did not get a response. Can anyone tell me if I am missing some information? or how I could improve it?
I want an instance from the next object to set a Label text in my current cell
cell.Label.text = talents(nextIndex).name //<- Something of this sort
Tried: passing array input to SectionController to use as
talents[index+1]
Error: File out of range
My Section Controller
class SectionController: ListSectionController {
var talents: Talent!
weak var delegate: SectionControllerDelegate?
}
extension SectionController {
override func sizeForItem(at index: Int) -> CGSize {
guard
let context = collectionContext
else {
return .zero
}
let width = context.containerSize.width
let height = context.containerSize.height
return CGSize(width: width, height: height)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCellFromStoryboard(withIdentifier: "HomeCell",
for: self,
at: index) as? HomeCell else {
fatalError()
}
cell.nameLabel.text = talents.name
cell.descView.text = talents.largeDesc
cell.shortDesc.text = talents.smallDesc
// let nextTalent = talents[index+1]
// cell.nextIntroFunc(nextlabels: nextTalent)
return cell
}
override func didUpdate(to object: Any) {
talents = object as? Talent
}
}
My ListAdapterDataSource
extension Home: ListAdapterDataSource {
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
print(talents)
return talents
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any)
-> ListSectionController {
return SectionController()
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
print("emptyView")
return nil
}
}
talents in the section controller isn't an array. It's just a single Talent, so calling [index + 1] on it is going to throw an error. (You might want to rename the property of the model in the section controller to talent so it's less confusing.)
Best practice for ListSectionController is to keep a 1:1 relationship between your object model and the section controller. If you want to have reference to the next object, you could create a cell/view model layer based on talent that includes reference to the next talent as well.
For example:
class TalentSectionModel: ListDiffable {
let talent: Talent
let nextTalent: Talent?
init(_ talent: Talent, nextTalent: Talent?) {
self.talent = talent
self.nextTalent = nextTalent
}
// whatever properties you want to expose
var name: String {
return talent.name
}
// example of exposing info about next talent
var nextTalentName: String? {
return nextTalent?.name
}
// ListDiffable protocol
// make sure to implement these two so diffing works
func diffIdentifier() -> NSObjectProtocol {}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {}
}
You could also just only pass in the necessary properties from the next talent without passing in the entire nextTalent if you don't want the section model to store the entire object.
Now with the TalentSectionModel you would map over your talents array in Home and return an array of view models in objects() under ListAdapterDataSource. Then, in your section controller you'll have the next talent's information available to you through the view model.
Resources:
ListKit Modeling and Binding (talks about the ListBindingSectionController, but also helpful to read for general understanding of model and section controller relationship),
ListKit best practices

App Crashes Due to Binding to Table Cell View

So I've created an NSOutlineView to display the file & directory list in a hierarchical way. I'm building a BitTorrent client (stating so the class names make sense).
As you can see, this is pretty much how the outline view looks:
The problem is associated with the Name column. In the name column, for each row, I have a checkbox and a text field side by side. This will help you get a clearer idea:
Now, I use bindings to get the value for each textfield. However, since there are 2 views (checkbox and textfield) that needs to bound to the same NSTableCellView, I'm returning a struct, from the data source, containing 2 values: a string for the text field (which holds the file/directory name), and a boolean for enabling/disabling the checkbox.
To handle the outline view (especially its data), I've set its class to TorrentContent, which is defined as below:
import Cocoa
struct Name {
let value: String
let enabled: Bool
}
class TorrentContent: NSOutlineView, NSOutlineViewDelegate, NSOutlineViewDataSource {
var content: [TorrentContentItem]
required init?(coder: NSCoder) {
let srcDir = TorrentContentItem("src")
let mainJava = TorrentContentItem("main.java")
let mainCpp = TorrentContentItem("main.cpp")
srcDir.children.append(mainJava)
srcDir.children.append(mainCpp)
content = [srcDir]
super.init(coder: coder)
delegate = self
dataSource = self
}
func outlineView(_: NSOutlineView, isItemExpandable item: Any) -> Bool {
if let _item = item as? TorrentContentItem {
if _item.children.count > 0 {
return true
} else {
return false
}
} else {
return false
}
}
func outlineView(_: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return content.count
} else {
if let _item = item as? TorrentContentItem {
return _item.children.count
}
}
return 0
}
func outlineView(_: NSOutlineView, child: Int, ofItem item: Any?) -> Any {
if item != nil {
if let _item = item as? TorrentContentItem {
return _item.children[child]
}
}
return content[child]
}
func outlineView(_: NSOutlineView, objectValueFor col: NSTableColumn?, byItem item: Any?) -> Any? {
if item != nil, col != nil {
if let _item = item as? TorrentContentItem {
switch col!.title {
case "Name":
return Name(value: _item.name, enabled: false)
default:
return nil
}
}
}
return nil
}
}
I've hard-coded the data so it'll be easier for you to understand what's going on.
Focusing only on the name column, here's the part of the above code which deals with that:
func outlineView(_: NSOutlineView, objectValueFor col: NSTableColumn?, byItem item: Any?) -> Any? {
if item != nil, col != nil {
if let _item = item as? TorrentContentItem {
switch col!.title {
case "Name":
return Name(value: _item.name, enabled: false)
default:
return nil
}
}
}
return nil
}
As you can see, it returns the Name struct, which contains values for both the views. I've hard-coded the enabled value to false just for testing purposes.
Now to bind that to the textfield's value property, I've done this:
My logic is that, since objectValue is an instance of the Name struct, objectValue.value should be the value of the Name struct's instance, which is a string.
I want to bind the enabled property of the checkbox in a similar way. However, none of the bindings work. They cause the app to crash. This is what XCode shows me after it crashes everytime I attempt to view the outline view during runtime:
Only got "(lldb)" in the console.
What am I doing wrong, and how do I achieve what I want? That is, setting the property values of multiple views from the data source class.
Cocoa Bindings uses Key Value Observing (KVO) and the observed object must be KVO compatible. See Using Key-Value Observing in Swift.
You can only use key-value observing with classes that inherit from NSObject.
Mark properties that you want to observe through key-value observing with both the #objc attribute and the dynamic modifier.
Solution A: Return a KVO compatble object from outlineView(_:objectValueFor:byItem:)
Solution B: Don't use Cocoa Bindings. Create a subclass of NSTableCellView and add a enabledCheckbox outlet. Set the values in outlineView(_:viewFor:item:).

Realm Array and child relationships

I am trying to make a List in relation to my realm array. I don't know if it is possible to take a hard coded realm array and give each string its own list. Currently I have my array in a table view and when a row is selected it segues to its own viewController. I am trying to get each selected row to contain its own list. Here's the code
Data Model 1
import Foundation
import RealmSwift
class DateChange: Object {
#objc dynamic var itemId : String = UUID().uuidString
override static func primaryKey() -> String? {
return "itemId"
}
let dates = List<String>()
let selection = List<Home>()
convenience init(tag: String) {
self.init()
}
}
Data Model 2
class Home: Object {
#objc dynamic var itemId : String = UUID().uuidString
override static func primaryKey() -> String? {
return "itemId"
}
var parentCategory = LinkingObjects(fromType: Home.self, property: "selection")
View Controller 1
class WeekOfViewController: NSViewController {
let post = DateChange(tag: "")
post.dates.append("December 30th - January 5th")
post.dates.append("January 13th - January 19th")
}
func numberOfRows(in tableView: NSTableView) -> Int {
return 2
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "dateCell") , owner: self) as! NSTableCellView?
cell?.textField?.stringValue = post.dates[row]
return cell
}
func tableViewSelectionDidChange(_ notification: Notification) {
self.performSegue(withIdentifier: "selectedDate", sender: self)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
// Unwrap the segue's identifier.
guard let identifier = segue.identifier else { return }
// Make sure this is the segue we care about.
if identifier == "selectedDate" {
let secondVC = segue.destinationController as! ViewController2
// Figure out which row was selected.
if let selectedRow = dateTableView?.selectedRow {
secondVC.selectedDate = post.dates[selectedRow]
}
View Controller 2
class ViewController2: NSViewController {
#IBAction func saveData(_ sender: NSButton) {
if let appendDate = selectedDate {
do {
try realm?.write {
let homeData = Home()
homeData.done = false
appendDate.dates.append()
}
} catch {
print("There was an error saving")
}
}
}
Yes. You can make multiple dimensional arrays.
Example:
1. Year object has a list of months
2. Month object has a list of days
3. Day object has a list of hours
4. etc, etc
When you app launches, you create a loop which initializes a Year, then initializes lots of months and appends them into the Year.Month_Array. Do the same for days_array in each month.
To save in Realm, call:
try! realm.write {
realm.add(Year)
}
Now you can read out you multi-level Realm object anytime you wish.
If my answer isn't clear, please let me know
The exact use case is a bit unclear but it seems that the app is a Master->Detail configuration where the master page contains a list of dates and then when a date is tapped, it segues to a detail page with further info.
Here's an example of code to handle the objects. You know how to populate a tableView with it's delegate methods so I'm omitting that part.
Suppose we want a list of events on the master page and then the activities of each event on the detail page. Start with two managed Realm objects; the event object which has a start and end date, the event title and the activities list within that event. Then there's the activity object.
class EventClass: Object {
#objc dynamic var start_date: Date?
#objc dynamic var end_date: Date?
#objc dynamic var event_title = ""
let activities = List<ActivityClass>()
}
class ActivityClass: Object {
#objc dynamic var title = ""
}
write an event with some activities to Realm
let formatter = DateFormatter()
formatter.dateFormat = "yyyymmdd"
let e0 = EventClass()
e0.event_title = "Workshop"
e0.start_date = formatter.date(from: "20180113")
e0.end_date = formatter.date(from: "20180119")
let a0e0 = ActivityClass()
a0e0.title = "Some activity"
let a0e1 = ActivityClass()
a0e1.title = "Another activity"
let a0e2 = ActivityClass()
a0e2.title = "Activity continues"
e0.activities.append(a0e0)
e0.activities.append(a0e1)
e0.activities.append(a0e2)
// write event 0 (e0) to realm which will create the event and activities
We are assuming both the master and detail views have tableViews, so load the events into the master tableView dataSource which is a Realm results class - it behaves like an array.
class ViewController: NSViewController {
var eventResults: Results<EventClass>? = nil
and then whenever it's time to populate the dataSource:
self.eventResults = realm.objects(EventClass.self)
and then the tableView delegate methods can get each row for display. It would look something like this on the master page
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "dateCell") , owner: self) as! NSTableCellView?
//cell?.textField?.stringValue = post.dates[row]
let event = self.eventResults[row]
cell.textField?.stringValue = "Event: \(title) from: \(start) - \(end)"
return cell
}
so then the tableView would look something like this
Event: Workshop from: 2018-12-30 - 2018-01-05
Event: Workshop from: 2018-01-13 - 2018-01-19
etc
when a row is tapped, get that event object from the master tableView datasource, self.eventResults
let tappedEvent = self.eventResults[tappedRowIndex]
and then get the activity list
let activityList = tappedEvent.activities
that activityList can be passed via the segue (or 1000 other ways) to the detail viewController and it becomes the dataSource for the detail tableView. The detail page follows the same pattern except the dataSource is the activities.
Does that help?

Protocol being reset in cell

I have a cell with a textField and a button. The button opens a page to collect data and has a protocol to pass that data back to the cell and fill the textField. That all works fine, however, when I come back the value is reset to zero. Print statements show that it is passing the data when it's set, but hitting Back clears it for some reason.
Protocol
protocol DistanceProtocol {
func distanceSet(distance: Double)
}
Call to protocol method
distanceProtocol?.distanceSet(totalDistance)
Cell class
class InputCell: CalculatorCell, DistanceProtocol {
#IBOutlet var textField: UITextField?
private var inputType = InputType.undefined
var viewController = UIViewController()
override func getHeight() -> CGFloat {
return 90
}
func distanceSet(distance: Double) {
print(distance)
textField?.text = "\(distance)"
}
func getInputType() -> InputType {
return inputType
}
func setInputType(inputType: InputType) {
self.inputType = inputType
}
#IBAction func walkTouched(sender: UIButton) {
let mapVc = viewController.storyboard!.instantiateViewControllerWithIdentifier("Map") as! MapLocationsViewController
mapVc.distanceProtocol = self
viewController.navigationController?.pushViewController(mapVc, animated: true)
}
}
As far as I can tell, everything is set up correctly. It's not reloading the cells in the tableView when I come back. Why is it resetting/how can I prevent it?
the text field is only set when you call the function. Unless you call this function in cellForRowAtIndex path it wont retain the value
I would likely implement it using a setter, do everytime the value is set, the label gets updated
protocol DistanceProtocol {
func distanceSet(distance: Double)
}
class CellWithText: UITableViewCell {
var cellText: String {
didSet {
textLabel?.text = cellText
}
}
}
extension CellWithText: DistanceProtocol {
func distanceSet(distance: Double) {
self.cellText = "\(distance)"
}
}
Then in your cellForRowAtIndexPath call you would call the function
cell.distanceSet(19.0)
i think you might try singleton design pattern or you can use struct for copying.