Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IBOutlet best practices

I would like to know which place is best for placing the IBOutlets from storyboards:

a) In the header file (.h)

b) In a class extension created on the .m file

Thank you

Regards

like image 307
apinho Avatar asked May 13 '15 11:05

apinho


People also ask

Should IBOutlet be weak or strong?

The official answer from Apple is that IBOutlets should be strong. The only case when an IBOutlet should be weak is to avoid a retain cycle. A strong reference cycle can result in memory leaks and app crashes.

What is the purpose of an IBOutlet?

IBOutlet is used when you want to do something with a View you created in Interface Builder. For example, you put a button in Interface Builder and you want to change it's caption/label from your code, attach IBOutlet (with a name such as button1) to that button. Then from your code, you can call [button1 dosomething].

What is the difference between IBOutlet and IBAction?

An IBOutlet is for hooking up a property to a view when designing your XIB. An IBAction is for hooking a method (action) up to a view when designing your XIB. An IBOutlet lets you reference the view from your controller code.

Why We Use weak in IBOutlet Swift?

weak outlet connection might be needed when creating custom views that has some reference to something back up in the view hierarchy and in general it is not recommended.


2 Answers

You have to keep in mind that .h is a public header.

So place your IBOutlet's there if they should be accessible by other classes.

However, even though you can do that. I would say that exposing the IBOutlet's in a public header is not a good practice (From object orientation perspective) since you are exposing some implementation details that should be only visible to whom is concerned about.

In short, placing the IBOutlet's in a class extension in the .m is a good practice.

like image 121
Otávio Avatar answered Nov 14 '22 15:11

Otávio


From Apple's Resource Programming Guide: Nib Files:

Outlets are generally considered private to the defining class; unless there is a reason to expose the property publicly, hide the property declarations a class extension.

like image 44
Ken Thomases Avatar answered Nov 14 '22 14:11

Ken Thomases