The way I understand auto reference counting is this:
If an object is going to be consumed by various classes, it should be type “strong” so that it stays around while others might be doing stuff with it.
If an object is simply an internal structure for a class, it can be type “weak”, because it will go away once the current class implementation is done dealing with it.
Is there more to it than this?
Here is an example of what I imagine:
#import "World.h"
@interface Foo : NSObject
@property (nonatomic, strong) NSArray *barArray;
@property (nonatomic, weak) NSString *bazString;
@end
@implementation Foo
-(void)sendTheArrayIntoTheWorld {
self.barArray = [NSArray arrayWithObject:@"lonely item"];
[World takeTheArray:self.barArray]; // array is strong so it can exist indefinitely
}
-(void)useThatString {
self.bazString = "weak old string"; // string is weak because it should be discarded when it's no longer needed here...
}
@end
This isn’t exactly how ARC works. It boils down to this:
strongreference to remain aliveweakproperty without referencing it elsewhere will result in its immediate deallocation, as with yourbazString. If you try accessing that string after you assign it a value (unless it is being owned by another object, like an array, which it is not in your case), you’ll find that it isnil.This means that weak references should be used for objects that you don’t necessarily ‘control,’ like delegates. If you use a strong reference for a delegate and the delegate has a strong reference on you, then neither object will ever be deallocated. This is called a retain cycle.
If you need an object to stay alive until you are done with it, use
strong. Otherwise, useweak.You can read much more about the intricacies and features of ARC here.