weak使用注意

来源:互联网 发布:神曲 知乎 编辑:程序博客网 时间:2024/05/04 12:45

一些控件作为属性使用weak修饰的时候:

@interface ZXQTableViewCell ()@property (nonatomic, weak) UIImageView *icon;@property (nonatomic, weak) UILabel *name;@property (nonatomic, weak) UIImageView *vipImg;@property (nonatomic, weak) UILabel *text;@property (nonatomic, weak) UIImageView *picture;@property (nonatomic, retain) NSMutableArray *array;@end
如果直接拿来使用:

_icon = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 50, 50)];[self.contentView addSubview:_icon];
这样是没有作用的。

原因是weak修饰的icon会在alloc、init之后立马释放掉(这与ARC有关)

所以解决办法是:

UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 50, 50)];[self.contentView addSubview:icon];self.icon  = icon;

1 0