在同“已分配"对象上多次调用初始化程序是否安全?
问题说明
我可以用 myImageView = [[UIImageView alloc] initWithImage:image];
以下影响显示的应用程序活动,如果我想更改 UIImageView 上的图像.我可以通过使用 myImageView.image = someNewImage
重新分配它来实现.然而,这似乎并没有更新框架尺寸.我可以手动修改它们,但我在实践中观察到调用 [myImageView initWithImage:someNewImage]
对我来说是这样做的,并且具有更简洁的优势.
Following application activity affecting the display, if I want to change the image on the UIImageView. I can do so by reassigning it with myImageView.image = someNewImage
. However this doesn't seem to update the frame dimensions. I can modify those manually, but I have observed in practice that calling [myImageView initWithImage:someNewImage]
does that for me, and has the advantage of being terser.
但是,我不确定在由单个 alloc 构造的对象上多次调用 init 方法是否正式违反了 Objective C 中的协议.除非它是安全的(保证不会崩溃或导致泄漏),否则我不会使用它.有证据表明它不安全吗?
However I not sure if it is officially a breach of protocol in Objective C to make multiple calls to init methods on an object constructed by a single alloc. I wouldn't use it unless it was safe (guaranteed not to crash or cause leaks). Is there evidence that it is unsafe?
我目前的研究...
This article gives general detail about 'alloc' and 'init' on objects
这是相关的 SO 问题
This is related SO question
为什么在Objective中alloc和init是分开调用的-C?
This blog article warns suppliers of objects that their init methods may be called multiple times as an effect of the initialization process.
http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so-much/
正确答案
没有
-init
假设它只被调用一次.例如,您引用的Apple文档中引用的-initWithImage
实现为
-init
is written assuming that it is only called once. For example, -initWithImage
quoted in Apple's documentation you quoted is implemented as
- (id)initWithImage:(NSImage *)anImage {
...
if (self) {
image = [anImage retain];
}
return self;
}
这假设 ivar image
不指向保留的对象.如果调用两次,它会泄漏image
.
This assumes that the ivar image
doesn't point to a retained object. If called twice, it leaks image
.
每个alloc
只调用一次-init...
,并在alloc
之后立即调用-init...
code> 像往常一样组合它们:
Call -init...
only once per alloc
, and call -init...
immediately after alloc
by combining them as usual:
SomeClass* foo=[[SomeClass alloc] init...: ... ];
您永远不应该将它们分开,因为 [anAllocedObject init...]
可能返回与 anAllocedObject
不同的内容.
You should never separate them, because [anAllocedObject init...]
might return something different from anAllocedObject
.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcgajjg
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20