Pop Flamingo
Pop Flamingo

Reputation: 2191

Why can't I access my application delegate from a ViewController?

In my app, I would like to access delegate methods from a View Controller, but when I try to access it this way :

let appDelegate = NSApplication.sharedApplication().delegate

I am getting nil, what could cause this ?

EDIT WITH ADDITIONAL INFO :
When I created the app, I did an error as I didn't choose to use storyboards, but when I needed them, I just added a storyboard file and defined it as the main interface, like this :
enter image description here

I believe my issue could come from here, could it be possible for the interface to be shown but not linked properly to the NSApplication (and so to the delegate) ?
If yes, how could I solve it ?

Thank you.

Upvotes: 2

Views: 339

Answers (1)

Renfei Song
Renfei Song

Reputation: 2960

In your storyboard, make sure that App Delegate's custom class (in the Identity Inspector) is set to your delegate class.

enter image description here enter image description here

Update

If you have just created a new storyboard, it will be empty. AFAIK there are no "standard" ways of creating the application scene. You have to copy it from another storyboard (they are just XMLs after all).

The simplest way would be creating a new project with Use Storyboard enabled, then right-click on your auto generated Main.storyboard, choose Open AsSource Code. After that, copy the <!--Application--> part to your empty Storyboard.storyboard. Don't for get to grab the header and footer part of it, too. Below is just an example.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="7706" systemVersion="14D136" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" initialViewController="B8D-0N-5wS">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="7706"/>
    </dependencies>
    <scenes>
    <!--Application-->

    <!-- your copied content -->

    </scenes>
</document>

Finally, right-click on your Storyboard.storyboard and choose Open AsInterface Builder - Storyboard to resume the normal design view.

Upvotes: 3

Related Questions