0

With reference to iOS 7 with ARC, is using temp or tempByProperty better?

In the .m file:

@interface ViewController ()

@property (weak) NSString *tempByProperty;

@end

@implementation ViewController

NSString *temp;

- (void)viewDidLoad
{
    [super viewDidLoad];
    temp = @"string1";
    temp = @"string2";

    self.tempByProperty = @"string1";
    self.tempByProperty = @"string2";
}

I've read that we should declare private variables in the .m file. But there seems to be two ways of declaring them (with and without the @property).

Which one will not cause a memory leak assuming the same variable will be overwritten multiple times with the = operator?

resting
  • 16,287
  • 16
  • 59
  • 90

2 Answers2

0

Use the property tempByProperty. The compiler automatically syntesizes for you. Also, use copy rather than retain when using NSStrings to prevent retaining mutable instances of your string.

Also, take a look at this good answer on deciding when to use ivars over properties: https://stackoverflow.com/a/8329900/244160

Community
  • 1
  • 1
Karl
  • 1,233
  • 8
  • 16
-2

Answer: Use tempByProperty.


I've read that we should declare private variables in the .m file.

Yes, you should declare private variables in .m file. And it is recommended to use @property after IOS4. You can put nonatomic, strong, weak, etc... So use @property. The other way is just reserved for backward compatibility.

Which one will not cause a memory leak assuming the same variable will be overwritten multiple times with the = operator?

Both of them will be fine. The new compiler will add autorelease so don't worry about the memory. But you use weak only when the property is owned by someone else. Otherwise, it will be released after been assigned. So in your case, tempByProperty will be nil afterwards (not what you want).

Most of the time you use weak only when it is a delegate property and it has to be weak. Otherwise you will retain the property and cause memory leak. It means you don't own the delegate. And it is probably not going to be your private property either.


You can read this EncapsulatingData from apple developer to get a better understanding of the property of object.

Ethan Fang
  • 1,271
  • 10
  • 15