0

Never initialize an object without reassigning any pointer to that object. As an example, don’t do this:

NSObject *someObject = [NSObject alloc];
[someObject init];

If the call to init returns some other object, you’ll be left with a pointer to the object that was originally allocated but never initialized.

Actually, this is a example in Apple's ObjC document, but i'm not quite clear with this, that is, why NSObject *someObject = [[NSObject alloc] init] can promise return the object we just needed, while NSObject *someObject = [NSObject alloc]; [someObject init]; can not?

abyn
  • 11
  • 3
  • Whenever I need to do [[.... alloc]init], I prefer [... new]. Saves typing and code looks smaller. If you need to do initWith... then no other option. – Anoop Vaidya Nov 09 '12 at 03:49
  • en, [[... alloc] init] is equivalent to [... new], if you just need a init-only object, which set the instance variables values to 0 if there is any. – abyn Nov 09 '12 at 04:03

1 Answers1

3

Just because -init could return something different from someObject. In your example you have to re-assign the pointer to the result of the -init.

Anton
  • 2,483
  • 2
  • 23
  • 35
  • But when and how it can return something different from someObject? And how to reassign the pointer to the result of the -init in that alloc init separated version? – abyn Nov 09 '12 at 04:12
  • i have already known the answer of this issue, what a stupid question ... – abyn Nov 24 '12 at 15:30