iPhone SDK:返回没有分配的 UILabel 的正确方法
我目前有一些代码,如下所示:
-(UIView)someMethod {
CGRectMake(0,0,100,100);
UILabel *label = [[UILabel alloc] initWithFrame:rect];
return label;
}
虽然它可以工作,但它显然会泄漏内存,需要修复。我认为修复方法是:
UILabel *label = [UILabel initWithFrame:rect];
但编译器告诉我 UILabel 不响应 initWithFrame。我想我的问题有两个:
a)正确的方法是什么,这样我就不会泄漏内存?
b
)我很困惑为什么 [UILabel alloc] 会响应 initWithFrame 而不是 UILabel 本身(我的理解是 UILabel 是从 UIView 继承的,它确实响应 initWithFrame)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
a) 你无法避免
+alloc
。但您可以使用-autorelease
放弃所有权。b)
+alloc
是类方法,-initWithFrame:
是实例方法。后者只能在 UILabel 的 (或者,用 ObjC 术语,发送到) 实例上调用。但是,符号“UILabel”是一个类,而不是一个实例,因此[UILabel initWithFrame:rect]
不起作用。同样,像+alloc
这样的类方法只能在类上调用,因此[label alloc]
不起作用。a) You can't avoid
+alloc
. But you can use-autorelease
to relinquish the ownership.b)
+alloc
is 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+alloc
can only be called on a class, so[label alloc]
won't work.也许更像是:
Maybe more like:
a)
b) 您误解了类方法和实例方法之间的区别。
类方法的声明和使用如下:
实例方法的声明和使用如下:
在您的示例中,
alloc
返回一个已分配的实例,然后您需要在该实例上调用适当的 init 实例方法。一些类提供了方便的构造函数,它们通常返回一个自动释放的实例:
但以这种方式重复代码并不常见,除非您正在处理诸如类集群之类的高级主题。当然,如果您发现经常需要特定的功能或方便的构造函数,那么将其添加到界面中可能是个好主意。
a)
b) you're misunderstanding the difference between a class method and an instance method.
a class method is declared and used like so:
a instance method is declared and used like so:
in your example,
alloc
returns an allocated instance, which you are then expected to call an appropriate init instance method on.some classes provide convenience constructors, which often return an autoreleased instance:
but it is not terribly common to duplicate code in this manner, unless you're working with advanced topics such as class clusters. of course, it may be a good idea to add this to the interface if you find you regularly need a particular functionality or convenience constructor.
只需使用您原来的方法即可
代替。
Just use your original method and use
instead.