I currently have some code that looks like:
-(UIView)someMethod {
CGRectMake(0,0,100,100);
UILabel *label = [[UILabel alloc] initWithFrame:rect];
return label;
}
While it works it obviously leaks memory and needs to be fixed. I thought the fix would be:
UILabel *label = [UILabel initWithFrame:rect];
But the compiler tells me that UILabel doesn’t respond to initWithFrame. I guess my question is two-fold:
a) What is the correct way to do this so I’m not leaking memory?
and
b) I’m confused as to why [UILabel alloc] would respond to initWithFrame but not UILabel by itself (my understanding is that UILabel is inherited from UIView that does respond to initWithFrame).
a) You can’t avoid
+alloc. But you can use-autoreleaseto relinquish the ownership.b)
+allocis a class method, and-initWithFrame:is an instance method. The latter can only be called on (or, in ObjC terminology, sent to) an instance of UILabel. However, the symbol “UILabel” is a class, not an instance, so[UILabel initWithFrame:rect]won’t work. Similarly, a class method like+alloccan only be called on a class, so[label alloc]won’t work.