1

What is the result of the following?

NSString *myStr = [[[NSString alloc] initWithString:@"Hello World."] autorelease];
myStr = [NSString stringWithString:@"Hello Again."];

Does myStr get correctly released or does this crash, since we would call autorelease on myStr which is now set to a string that is already autoreleased?

jscs
  • 63,694
  • 13
  • 151
  • 195
VTS12
  • 452
  • 8
  • 22
  • Just use ARC, it will fix all of these problems. Backwards compatibility is much more of a hassle than just using what apple recommends (ARC). – Richard J. Ross III Mar 14 '12 at 18:02
  • @RichardJ.RossIII Not entirely true in all cases. For instance some third party libraries do not support ARC. Memory management is still a necessary concept in iOS. – Mike D Mar 14 '12 at 18:06
  • @MikeD just compile the libraries with -fno-objc-arc. ARC is still the best way to go. – Richard J. Ross III Mar 14 '12 at 18:08
  • Our app is pretty huge and I think transitioning to ARC would take a long time. According to static analyzer, we currently have 500+ memory issues that I'm working on fixing : – VTS12 Mar 14 '12 at 18:17
  • Interesting question (although fairly easy to test out). – jscs Mar 14 '12 at 18:22

1 Answers1

4

Your code example works the way you would expect. autorelease can't somehow change what object it refers to after you send the message. The @"Hello World." and @"Hello Again." objects are different objects, even though your example uses the same pointer variable to refer to them.

CRD
  • 52,522
  • 5
  • 70
  • 86
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • So technically the autorelease will get sent to "Hello World.", right? – VTS12 Mar 14 '12 at 18:04
  • "get sent to"? It already *has* been sent. It's not like the message gets queued up to get sent later or something. – Carl Norum Mar 14 '12 at 18:05
  • I mean, when the autorelease pool starts, it will call release on "Hello World."? – VTS12 Mar 14 '12 at 18:06
  • Yes, I just want to make sure release isn't being sent twice and I don't think it is. Thanks for your help. – VTS12 Mar 14 '12 at 18:10