0

the code is just simple:

@interface Test : NSObject
@property (nonatomic, strong) NSString * str;  //strong
//@property (nonatomic, weak) NSString * str;  //weak
-(void)func;
@end

@implementation Test
@synthesize str = _str;
-(void)func{
   _str = @"test string";       // using ivar
   //self.str = @"test string"; // using setter
}
@end

there are four situations in the code above, strong/weak, ivar/setter

which types will cause memory leaks ?

which types are the same ?

I have test the code with NSLog but all run well (no nil printed) , why ? maybe about autorelease ?

--------------edit---------------

i read the document and find that "string constant would be never deallocated"

so the code act different when string initializes with initWithString or initWithFormat (and the code i wrote is wrong )

the weak property always be nil when using initWithFormat

for memory management ivar and setter are the same: Is self.iVar necessary for strong properties with ARC?

Community
  • 1
  • 1
kran
  • 259
  • 4
  • 14
  • How did you test it? By having a string literal value (something like `@"hello world"`)? If you used a string literal then your "test" is broken because they _never_ get released... – David Rönnqvist Jun 10 '12 at 21:45
  • 1
    String properties are usually copied instead of retained. Having a retained value that someone else could change might not be what you want. You can argue about what is "necessary" but it is good practice to use setter since it enforces the behavior you have defined for the property (like releasing the old value and retaining or copying the new value). Using setters and getters will also make sure that KVO works. If you just change the variable, KVO won't work. – David Rönnqvist Jun 10 '12 at 21:50

2 Answers2

0

If you're using ARC the system handles the memory and won't report as a leak. Here's a good writeup to check out about the ARC and the difference between strong and weak references.

http://www.quora.com/Objective-C-programming-language/In-Objective-C-whats-the-difference-between-a-strong-and-weak-pointer

skram
  • 5,314
  • 1
  • 22
  • 26
  • I read this article , now in my mind the `weak` should be the wrong way, object will be released earlier, but if `_str` is same to `self.str` in the `strong` case ? – kran Jun 10 '12 at 18:04
0

I always get confused over this too, however I think basically weak means it will go away when the class is set to nil, whereas strong won't let the class go away until the var is also removed as it has a +1 retain count to start with.

You can't really ask which will cause leaks as neither will when used properly and both can of not used properly.

Darren
  • 10,182
  • 20
  • 95
  • 162