4

Are there a differences between these two lines of code?

__weak IBOutlet UITextField *usernameField;

@property (weak) IBOutlet UITextField *usernameField;

What if you declare either of these in interface section of the .h or the .m files?

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281

2 Answers2

6

Yes. The first example declares a weak instance variable called usernameField, but the second declares a weak property called usernameField, and an instance variable called _usernameField that is accessed by the property.

If you declare it in an @interface section of the .m file, then it can only be accessed in that .m file (unless you mess with the Objective-C runtime).

NobodyNada
  • 7,529
  • 6
  • 44
  • 51
  • Would you say a property in objective c is analog to a static class variable in Java? –  May 29 '14 at 23:05
  • That doesn't make sense, a static field in java means not particular to any instance, therefore not an instance variable. Are you saying an instance variable in objective c is not particular to any instance of that class? –  May 29 '14 at 23:09
  • 1
    Sorry, I accidentally posted a comment before I was done typing it. An instance variable in Objective-C is associated with an instance, just like in Java. A property is an instance variable, paired with (usually auto-generated) accessor methods. Objective-C doesn't have static class variables, but if you want one, see [Objective C Static Class Level variables](http://stackoverflow.com/q/1063229/3476191). – NobodyNada May 29 '14 at 23:14
  • Gotcha, I actually stumbled upon this question trying to create private instance variables for classes. Particularly, variables representing UI objects such as UITextFields and the like, figured there's no reason to have them in public .h files. –  May 29 '14 at 23:20
  • ... a weak instance variable also notably isn't available to the NIB loader. It's a fully dynamic runtime in which interfaces are loaded as data, not a round-the-back write some hidden code hack. So there's no point declaring one as `IBOutlet`. – Tommy May 29 '14 at 23:53
2

The difference is not in the weak reference but just in the fact that the first is an instance and the second is a @property.

__weak and (weak) is the same thing, but the second is used as attribute for properties.

Matteo Gobbi
  • 17,697
  • 3
  • 27
  • 41