2012-08-27 48 views
2

我有我的自定义UIButton类中的UIImageView和UILabel。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永远是零转让之后。

如果我使用一个临时变量,然后分配给属性,它工作得很好:

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和我不知道这有什么错在第一次使用。任何建议,将不胜感激!

+0

你在哪里初始化标签和形象?鉴于没有加载? –

+0

是的。它在viewDidLoad方法中 – xxris

回答

1

从您的描述中可以看出您正在使用ARC,并且这两个属性/实例变量被声明为weak(或__weak)。这就是为什么强大的局部变量会隐含地阻止对象被提前释放。

由于您的自定义按钮计划保留图片和标签,因此您应通过从其声明中删除weak来制作属性/实例变量strong

+0

你是对的!我将“弱”改为“强”,现在它完美了! – xxris

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]; 
+0

谢谢!我认为我犯的主要错误是使用“弱”而不是“强”财产。 – xxris