When not to alloc and init an NSString

前端 未结 4 1681
北海茫月
北海茫月 2020-12-16 06:29

Whenever I need to create a new NSString variable I always alloc and init it. It seems that there are times when you don\'t want to do this. How do you know when to alloc an

4条回答
  •  长情又很酷
    2020-12-16 06:55

    It seems that there are times when you don't want to do this.

    I can't think of any time when I would want to alloc/init a NSString. Since NSStringgs are immutable, you pretty much always create new strings by one of:

    • convenience class method e.g.

      NSString* foo = [NSString stringWithFormat:...];
      
    • literal

      NSString* foo = @"literal";
      
    • NSString instance method

      NSString* foo = [bar uppercaseString];
      
    • copy from mutable string

      NSString* foo = [mutableBar copy];  // foo needs to be released or autoreleased in this case
      

提交回复
热议问题