I have an UIImageView and an UILabel in my customized UIButton class.
However, if I have code like the following
self.productImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
self.productName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
The self.productImage and self.productName will always be nil after the assignment.
If I’m using a temporary variable and then assign to the property, it works well:
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;
I’m new to objective-C and I’ve no idea what’s wrong with the first usage. Any suggestions would be appreciated!
From your description it sounds like you are working with ARC, and both properties / instance variables are declared as
weak(or__weak). That is why local variables which are strong implicitly keep the objects from being released early.Since your custom button plans to keep the image and the label, you should make both properties / instance variables
strongby removing theweakfrom their declarations.