1

I want to deffine a bool variable and set default value for it. I can do this

First

@implementation ViewController1

BOOL var1 = false;

Second

And I can add it in ViewController1.h file

@property (nonatomic, assign) BOOL var1

Is it possible to set default value in second way

What is difference between these two?

Fattaneh Talebi
  • 727
  • 1
  • 16
  • 42
  • probably a duplicate of https://stackoverflow.com/a/11478172/1214122 – holex Oct 23 '18 at 12:36
  • What is the purpose of `var1`? – Willeke Oct 23 '18 at 12:51
  • @Willeke it is an example. I just want to learn it. Why should not use with first way? – Fattaneh Talebi Oct 23 '18 at 12:54
  • Is your question how an instance variable is different from a property (which you ask in the question itself) or reasons to use one over the other (which you ask in your comment above)? – David Rönnqvist Oct 23 '18 at 12:57
  • 1
    @holex @DavidRönnqvist the first `var1` is a global variable, not an ivar. – Willeke Oct 23 '18 at 13:00
  • Note that the answer to "how an instance variable is different from a property" will depend slightly on the variables type (if it's a primitive—like `BOOL` or `NSInteger`—or if it's an Objective-C object—like `NSString`, `NSArray`, or `UIView`). Consider updating your question to mention if this difference matters to you. – David Rönnqvist Oct 23 '18 at 13:01
  • @DavidRönnqvist Thanks. Yes. and could you please look at this problem https://stackoverflow.com/questions/52947759/why-value-of-property-is-kept-when-viewdidload-is-called-again – Fattaneh Talebi Oct 23 '18 at 13:01
  • @Willeke I'm wasn't sure if that was the OP's intention or if the OP meant to declare an instance variable instead. – David Rönnqvist Oct 23 '18 at 13:02
  • @ Willeke you mean that with first way I created a global variable which is not related to a specific class? – Fattaneh Talebi Oct 23 '18 at 13:04
  • 1
    Yes, an ivar is declared inside `{}`. – Willeke Oct 23 '18 at 13:40
  • @Willeke, soooo, is that question about why one should do _encapsulation_ rather than _polluting the global namespace_...? – holex Oct 23 '18 at 14:06
  • @helex I actually didn't know that with first way I declare a global variable – Fattaneh Talebi Oct 23 '18 at 14:09

1 Answers1

1

First way is global. That means you have potential to disturb other library or framework that you use in your app.

Second way is the correct way to do it but of course it limits to only your class. Also memorywise, is better.

Also, if you want "global" variable, use singleton. :D

GeneCode
  • 7,545
  • 8
  • 50
  • 85