2

我的自定义 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 的新手,我不知道第一次使用有什么问题。任何建议,将不胜感激!

4

2 回答 2

1

根据您的描述,听起来您正在使用 ARC,并且两个属性/实例变量都被声明为weak(或__weak)。这就是为什么强的局部变量隐式地阻止对象被提前释放。

由于您的自定义按钮计划保留图像和标签,因此您应该通过从它们的声明中strong删除来创建属性/实例变量。weak

于 2012-08-27T11:44:15.800 回答
0

尝试一下 :

NSURL *imageurl = [NSURL URLWithString:@"http://www.chakrainteractive.com/mob/ImageUpoad/pic2-2.png"];

NSData *imagedata = [[NSData alloc]initWithContentsOfURL:imageurl];

UIImage *image = [UIImage imageWithData: imagedata];

[logoImg setImage: image];
于 2012-08-27T12:03:14.853 回答