我的自定义 UIButton 类中有一个 UIImageView 和一个 UILabel。
但是,如果我有如下代码
self.productImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
self.productName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
self.productImage 和 self.productName 在分配后将始终为 nil。
如果我使用临时变量然后分配给该属性,则效果很好:
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
self.productImage = imgView;
UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
self.productName = name;
我是 Objective-C 的新手,我不知道第一次使用有什么问题。如有任何建议,我们将不胜感激!
最佳答案
根据您的描述,听起来您正在使用 ARC,并且两个属性/实例变量都声明为 weak
(或 __weak
)。这就是为什么强局部变量隐式地阻止对象被提前释放的原因。
由于您的自定义按钮计划保留图像和标签,因此您应该通过从它们的声明中删除 weak
来使两个属性/实例变量都strong
。
关于objective-c - 直接分配和分配时,UIImageView/UILabel 属性始终为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12140998/