开发者

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?


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;"


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.


IBOutlet is defined as nothing. Command-click on the word in Xcode to see its definition.

Which is to say, it's just a hook so interface builder knows to show it. I've never seen an @property which included IBOutlet, but I imagine it's for situations like UIViewController's @property view which needs to be accessible from IB, but can also be assigned at runtime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜