Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IBOutlet instance variables in implementation (.m) files

Let’s say I have a view controller, or a window controller, which is (as usual) the “File’s Owner” in a corresponding XIB file.

It is (as you all know) very common to have IBOutlets in the controller class that you can then connect in the XIB using Interface Builder.

Until now, I have been creating IBOutlet instance variables in my interface (.h) files. But (as you all know) IBOutlets are very often a private mechanism of the controller class; outsiders shouldn’t even know about them.

This is why I now—since Objective-C recently started offering the capability to do so—want to put all of my IBOutlets into my implementation (.m) files.

I tried doing this, and this seems to work fine. My questions are these: Why does this work? I was under the impression that Interface Builder could only view the class’ header files—not peek into their implementation files. Am I wrong? How come that Interface Builder can “see into” implementation files? Could it be potentially dangerous to put IBOutlet instance variables into the implementation files?

like image 681
Enchilada Avatar asked Jan 03 '12 21:01

Enchilada


1 Answers

From Xcode 4 User Guide

Note: Because Xcode 4 parses both your header files and implementation files for indexing, you can define actions and outlets in implementation (.m) files without needing to place them in the header file and you can make connections directly from the nib file to the implementation file. Therefore, you do not need to expose parts of your interface or actions to clients who might be using your classes.

And for Could it be potentially dangerous to put IBOutlet instance variables into the implementation files?

Yes it is, but not that much as any declared method can be accessed because of the lack of access-scope at runtime. Even if the method isn't accessible, the resolution is done at runtime and no access-scope information is attached to the method. That could have been implemented, but Objective-C lacks of private, protected and so on as in C++ or Java. Note that implementing such a behavior would be even much slower at runtime.

like image 75
Geoffroy Avatar answered Nov 04 '22 10:11

Geoffroy