-1

I am just wonder what is the difference between [[UIImageView new] init] and [[UIImageView alloc] init] .

is memory allocated in [[UIImageView new] init] as well ?

Muhammad Saad Ansari
  • 1,748
  • 3
  • 13
  • 20
  • 3
    Well, what did the documentation say? –  Jun 16 '13 at 06:46
  • possible duplicate of [Use of alloc init instead of new](http://stackoverflow.com/questions/719877/use-of-alloc-init-instead-of-new) – Laszlo Oct 21 '15 at 08:51

1 Answers1

3

+ new is equivalent with + alloc followed by - init, so

UIImageView *iv = [[UIImageView alloc] init];

and

UIImageView *iv = [UIImageView new];

are right (and equivalent) and

UIImageView *iv = [[UIImageView new] init];

is wrong, since it calls - init twice.

  • will new] init] compile? I didn't try. – Anoop Vaidya Jun 16 '13 at 07:03
  • @AnoopVaidya Why wouldn't it? –  Jun 16 '13 at 07:13
  • I assumed compiler to be intelligent, and it should avoid leak, two init in one line (In ARC, it is fine) but in MRC leak is probable, isn't it? – Anoop Vaidya Jun 16 '13 at 07:14
  • @AnoopVaidya Compiler has no knowledge of runtime... And yes, calling `init` twice does very well have the risk of leaking memory. –  Jun 16 '13 at 07:15
  • A doubled (or more) call to -init doesn't call through to retain. There will never be a memory leak. Memory management semantics reside in assignment and allocator functions, but that's it. – CodaFi Jun 16 '13 at 08:27
  • @CodaFi Huh what? What if I do `_someIvar = [[Foo alloc] init];` inside `- init`? Like [this](https://github.com/H2CO3/HCDownload/blob/master/HCDownloadViewController.m#l45)? –  Jun 16 '13 at 08:48
  • Retention occurs because the +1 initialized object is assigned to an implicitly strong local (+2). ARC should balance that out to +1 – CodaFi Jun 16 '13 at 10:21
  • 1
    @CodaFi And if I don't use ARC? (Hey, you **know** I don't!) –  Jun 16 '13 at 10:21
  • Then the initialized variable is assigned to an implicitly `assign` local, and it remains +1. If you go through the setter, then you have to autorelease it back down to +1 – CodaFi Jun 16 '13 at 10:22
  • 1
    @CodaFi Yes, that's right. That's why I pointed you to a line where it does **not** go through the setter :) Let's agree on that both of us are right ;) –  Jun 16 '13 at 10:23