0

I'm aware that, when setting instance variables (such as NSString variables) in ObjC classes, it's often best practice to ensure the class owns its own variables, e.g.:

NSString *someInstanceVariable = [NSString stringWithString: someNSStringObject];

My question is, is this different (practically speaking) from the following?

NSString *someInstanceVariable = [someNSStringObject copy];
jscs
  • 63,694
  • 13
  • 151
  • 195
max_jf5
  • 169
  • 1
  • 12
  • 1
    The end result is identical. Both protect you if `someNSStringObject` is really a mutable string. – rmaddy Aug 17 '14 at 16:41
  • Related: [+\[NSString stringWithString:\] -- what's the point?](http://stackoverflow.com/q/1616348) – jscs Aug 17 '14 at 16:54
  • 2
    If you are working with a non-ARC codebase, `stringWithString:` returns an autoreleased value, while `copy` does not. Beyond that there really isn't any difference. – BergQuester Aug 17 '14 at 16:55
  • rmaddy and BergQuester - as I suspected, but wanted to check. Thanks! – max_jf5 Aug 17 '14 at 17:10

1 Answers1

2

+[NSString stringWithString:] never returns nil.

[someString copy] returns nil if someString is nil.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • 2
    However, `stringWithString:` will throw an exception (app crash), if the parameter is `nil`. – rmaddy Aug 17 '14 at 17:29