Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a IBOutlet in Objective-C

The code generator Accessorizer has an option to assign IBOutlets rather than retaining them. For example, compare these two generated lines:

@property(nonatomic,retain)IBOutlet UIImageView *backgroundView;
@property(nonatomic,assign)IBOutlet UIImageView *backgroundView;

Why would I want to assign IBOutlets, while retaining all other properties?

like image 765
Casebash Avatar asked Jan 21 '10 03:01

Casebash


2 Answers

Usage depends on the platform as specified in the memory management guide :

"The behavior of outlets depends on the platform (see “Mac OS X Desktop” and “iPhone”), so the actual declaration differs:

  For Mac OS X, you should use:

  @property (assign) IBOutlet UserInterfaceElementClass *anOutlet;

  For iPhone OS, you should use:

  @property (nonatomic, retain) IBOutlet UIUserInterfaceElementClass *anOutlet;"
like image 59
Tyr Avatar answered Oct 23 '22 12:10

Tyr


On the iPhone OS, your view may get unloaded (under low memory conditions), but if you have state that you care about in some of your views connected to outlets, you don't want to lose it. So you want to retain them.

Say a navigation controller. The root view gets unloaded from a low memory warning sent to the controller but there is a bunch of controller above it on the stack. When you pop back to root, it reloads the view and sticks your outlets back where they were in the same state they used to be in.

At least, I think this is the technical reason.

But in a more general sense, your controller cares about these views, because it wants to interact with them. And that fact alone means that you want to retain them, and release them when you no longer care. It's just good practice.

like image 42
Alex Wayne Avatar answered Oct 23 '22 12:10

Alex Wayne