I have three ways of writing this code. The third way confuses me.
First way works fine.
//.h
@property (weak, nonatomic) IBOutlet UIImageView *picImageStage;
//.m
NSString *name = [NSString stringWithFormat:@"allen.png"];
UIImage *image = [UIImage imageNamed:name];
UIImageView *t = [[UIImageView alloc]initWithImage:image];
self.picImageStage = t;
Second way works fine.
//.h
@property (retain, nonatomic) IBOutlet UIImageView *picImageStage;
//.m
NSString *name = [NSString stringWithFormat:@"allen.png"];
UIImage *image = [UIImage imageNamed:name];
self.picImageStage = [[UIImageView alloc]initWithImage:image];
Third way turns wrong.
//.h
@property (weak, nonatomic) IBOutlet UIImageView *picImageStage;
//.m
NSString *name = [NSString stringWithFormat:@"allen.png"];
UIImage *image = [UIImage imageNamed:name];
self.picImageStage = [[UIImageView alloc]initWithImage:image];
I don’t understand the reason. Could anyone help me? Thanks 😀
In the 3rd snippet you have declared the @property as weak, and the UIImageView will be deallocated immediately. Because a weak relationship will be nil’d when there is no strong relationship to the same object.
In the 1st snippet, which is almost the same, you assigned the UIImageView to a local variable first. This local variable uses a strong relationship implicitly. If you leave the scope of the local strong variable (i.e. the method where you run this code) the property will be deallocated too, except if you create another strong assignment before leaving the scope of the variable. Which will for example happen if you add the UIImageView as a subView of another view. Adding a view to another creates a strong relationship.