NSString 最美的创建方式也是最毒

3 Comments

今天睡觉前,看到一位学妹在淫淫网站上发了一篇关于Cocoa开发的技术文章,在这里http://blog.renren.com/blog/251384541/715015230,问为什么在代码中很少看到这样创建一个NSString对象的:

NSString *str = @”I LOVE TJAC”;

这是最简单最美丽地创建一个NSString对象的方法,估计也是列为开发人员最喜欢用的方式,而且应该很多人至今都还这样用。但是这样做其实是有很大的缺陷的。在官方String Programming Guide中是这样说的:

—————————————————————————————————————–

 

The simplest way to create a string object in source code is to use the Objective-C @”…” construct:

NSString *temp = @”/tmp/scratch”;

Note that, when creating a string constant in this fashion, you should avoid using anything but 7-bit ASCII characters. Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated, though you can retain and release them as you do any other object. You can also send messages directly to a string constant as you do any other string:

BOOL same = [@"comparison" isEqualToString:myString];

—————————————————————————————————————–

 

所以如果你的程序中有这样的方式赶紧改过来吧,如果你觉得用类似与[NSString StringWith....]这样函数很麻烦,那么你可以些这样一个宏来简化你的工作:

#define OC(str) [NSString stringWithCString:(str) encoding:NSUTF8StringEncoding]

于是就可以方便使用了:NSLog(@”%@”, OC(“Hello World!”) );

3 Comments (+add yours?)

  1. dpcao
    三 11, 2011 @ 18:50:09

    NSString has several methods with “C string” in the name, such as +stringWithCString: and -cString. Please don’t use them. They use the “system encoding”, which is not defined to be anything in particular, and so these methods will not behave in a predictable manner when used with non-ASCII data. Instead, use their counterparts, +stringWithUTF8String and -UTF8String. The UTF8 variants of these methods behave in a predictable and useful manner on non-ASCII data, and produce exactly what you want when used on ASCII data.

    回复

    • Near
      三 13, 2011 @ 00:32:50

      yeah u r right, and apis as +stringWithCString: -cString are all deprecated in the new sdks.

  2. MagicYang
    二 18, 2012 @ 23:10:56

    因为通过NSString *temp = @”/tmp/scratch”;方式定义的变量,在编译的时候分配内存区域为字符常量区,在编译的时候就分配好了,但在实际开发中这点开销其实可以忽略的

    回复

Leave a Reply

使用新浪微博登录
  • RSS
  • Twitter
  • Buzz
  • LinkedIn
  • Flickr