• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在同“已分配"对象上多次调用初始化程序是否安全?

用户头像
it1352
帮助1

问题说明

我可以用 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

http://developer.apple.com/library/mac/documentation/cocoa/Conceptual/ObjectiveC/Articles/ocAllocInit.html

这是相关的 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/

正确答案

#1

没有

-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
系列文章
更多 icon
同类精品
更多 icon
继续加载