-4

Possible Duplicate:
Why are these two NSString pointers the same?

Will the memory addresses of s1 & s2 be same?

If Yes, then Why?

What if both strings are mutable?

NSString *s1 = @"Hello";

NSString *s2 = [[NSString alloc]initWithString:@"Hello"];
Community
  • 1
  • 1
Deepak
  • 348
  • 4
  • 14
  • 4
    possible duplicate of [Why is NSString stringWithString: returning pointer to copied string?](http://stackoverflow.com/questions/11890814), [Why are these two NSString pointers the same?](http://stackoverflow.com/questions/11605851/), and [Difference between NSString literals](http://stackoverflow.com/questions/8032375/), probably [among others](http://stackoverflow.com/search?q=%5Bobjc%5D+nsstring+address+same&submit=search) – jscs Aug 11 '12 at 19:20

1 Answers1

2

Will the memory addresses of s1 & s2 be same?

maybe -- implementation is defined by Foundation.

If Yes, then Why?

the implementation may return the parameter when and if no copy needs to be made -- the object you request behaves identical to the input parameter when the input parameter is an immutable NSString. when passing the immortal NSString literal as you have done, the implementation could easily determine that the parameter is immutable, and opt to return the parameter (retained).

of course, that's an optimization the library (Foundation) would need to recognize and support.

it's also possible that the implementation may elect not to return the input parameter, due to variances in implementation details. as one example, the implementation may return a new string if the string were created using an externally owned character buffer. it may also recognize the parameter is mutable, then would of course need to return a new immutable object representation.

What if both strings are mutable?

then deep copying is more probable -- implementation is defined by Foundation. however, you will have unique instances (their addresses will not match).

justin
  • 104,054
  • 14
  • 179
  • 226