rollingcodes
rollingcodes

Reputation: 16008

When would you declare variables in package instead of as properties?

I have noticed in many of the header documentation files in the Apple framework that define variables within brackets directly following the interface definitions like the variables a and b below:


@interface MyView : UIView  {
  @package
  int a;
  UIView b;
}

Normally I have just been declaring all variables as properties for the convenience of the synthesized methods. Can anyone tell me when it would be more efficient or more proper to declare variables under @package instead of as @properties?

Upvotes: 0

Views: 39

Answers (1)

Justin Johns
Justin Johns

Reputation: 406

@package is an access specifier, similar to how it works in Java (it allows access from any code at the same package level). But since the . syntax with Objective C objects works with properties, and not direct member access, you have to use the -> syntax instead, as if the object were a C struct, to access that variable directly.

An auto-synthesized @property instead creates a protected instance variable (prefixed with an underscore), which is read and set by the synthesized methods. Now, the overhead of using a property is negligible, compared with direct member access, so there's no real reason to stop using properties.

In your example, if you had a MyView* myview, you could set the view b directly, with myview->b = someotherview;. But this would give the class no chance to respond to the update (you would probably write the setter method so you can do something with it), nor does it ensure that the view provided is retained properly. These are the issues that properties were designed to avoid.

Upvotes: 1

Related Questions