unichar and NSString - how interchangeable are these?

后端 未结 3 1197
鱼传尺愫
鱼传尺愫 2020-12-13 04:08

There is an NSString method -characterAtIndex: which returns an unichar.

  • (unichar)characterAtIndex:(NSUInteger)index
3条回答
  •  攒了一身酷
    2020-12-13 04:55

    NSString is really a class cluster. That means for various reasons including performance based on content and size and to support toll free bridging to CFString when you create an NSString you may actually get one of many private classes that return YES to isKindOf: when you ask it if it is an NSString and it will respond to all of the methods in the NSString class. It's like a Protocol but all objects will say and do and be NSString in the public API.

    As the documentation states for NSString and CFString it is conceptually an array of UTF16 unichar It may and will use a different internal representation where it presents an advantage to the implementation. Usually performance sometimes memory size. But you can rely on it giving you a C array of unichar when asked or anything else the API promises.

    It's had a long time to mature and is tweaked internally in nearly every release.

    In short yes you can think of it as being backed by an array of UTF16 unichar largely matching the description of a logical string in the Unicode standard. But the thing to keep in mind is that you really should not need to worry what's inside, only what it tells you is inside.

    It's one of the best implementations of Unicode. If you want a fuller picture of how it works you can look at ( most ) of the source of CFString at opensource.apple.com It's C and Core Foundation (object oriented C) and fairly stylized, so don't expect to understand it all at once.

    NSString and CFString do have methods to return and create from unichar. Most people should not need those most of the time. If you do, be careful, be prepared to read a lot and to make naive mistakes. Unicode is a big topic. Handling it correctly is a science and an art at that level. That is one of the reasons for NSString. It handles a lot of the hard stuff so you do not have to so often, unless you want to or need to.

提交回复
热议问题