Why Apple's sample code project IKImageViewDem

2019-08-05 10:47发布

问题:

I have studying how to use IKImageView in my app. I downloaded the following demo from Apple site.

https://developer.apple.com/library/mac/samplecode/IKImageViewDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS10004049

One thing I do not understand is: This project has only implemented a Controller class.

@interface Controller : NSObject
{ 
 ...

I do not understand how does it work at all. If I create a new project in XCode, it will usually generate an AppDelegate class which implements NSApplicationDelegate interface.

I do not know if I understand the mechanism correctly.

Does the following steps describe how it works?

1) In info.plist it specifies the main bundle is MainMenu.xib.

2) the Window is binded to the Controller like so

3) When the application starts, it loads the Windows from the MainMenu.xib and the Controller class takes over the windows interaction from there.

回答1:

It's really old sample code. It predates Xcode project templates generating an app delegate for you. Back then, early Xcode and ProjectBuilder (the old name for it) Left it up to you to do that.

Lots of older sample code has this sort of thing. As long as things get kickstarted by nib loading, magic happens, objects are instantiated and connected

If you have a simple controller that inherits from NSObject and it has a proxy in you main nib file, it will get created. If you also connect its proxy as delegate to some view or control in the nib, all of that happens.

You don't technically need an object that is the delegate of you NSApplication object. But in reality it is a good best practice and any non trivial app will have that and a lot more.

There's a lot of magic that happens when the C function NSApplicationMain() is called at the launch of your app.

The old and in many ways out if date book Cocoa in a Nutshell covers this well.



回答2:

Yeah you pretty much describe how it works and what it's doing.

It's relying on the fact that NSApplicationDelegate is an informal protocol and it doesn't declare that Controller conforms to it and is using the NIB to kick-start the app.