在同一个 'alloc'ed 对象上多次调用初始化程序是否安全? [英] Is it safe to call initializers multiple times on the same 'alloc'ed object?

查看:55
本文介绍了在同一个 'alloc'ed 对象上多次调用初始化程序是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我目前的研究...

本文提供了关于对象上的alloc"和init"的一般细节

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?

这篇博客文章警告对象的供应商,他们的 init 方法可能会被多次调用作为初始化过程的影响.

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.

这篇关于在同一个 'alloc'ed 对象上多次调用初始化程序是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆