Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

iphone - unichar and NSString - how interchangeable are these?

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

  • (unichar)characterAtIndex:(NSUInteger)index

I wonder if this unichar, which obviously is not an NSString, can be converted into an NSString or feeded to an NSString for comparing purposes?

And: Does an NSString internally just consist of an array of unichar items?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have two options: the first is a category adding a stringWithUnichar method to NSString:

@interface NSString (MNNSStringWithUnichar)
+ (NSString *) stringWithUnichar: (unichar) value;
@end


@implementation NSString (MNNSStringWithUnichar)

+ (NSString *) stringWithUnichar:(unichar) value {
     NSString *str = [NSString stringWithFormat: @"%C", value];
     return str;
}

@end

Then call it with

NSString *otherString = @"TestString";

NSString *str = [NSString stringWithUnichar:[otherString characterAtIndex:1]];

or you could just directly go like this:

NSString *str = [NSString stringWithFormat:@"%C",[otherString characterAtIndex:1]];

Choose the category if you want to use it repeatedly, or if you only have to do it once, use the stringWithFormat example!!

Not to sure about the internals of NSString, but I'd guess it is probably wrapping a

unichar *

or an array of unichars (like a C char *)

A unichar is simply a 16bit value that is used to store a character. Unlike an unsigned char which is only 8 bits, it can hold more than 0-255, so it can hold unicode characters as well, which are 16bits. A NSString is a (cluster of) class[es] that contains an array of unichars

EDIT

Here are a few articles about what people think an NSString is:

http://cocoawithlove.com/2008/08/string-philosophies-char-arrays.html

http://www.reddit.com/r/programming/comments/6v1yw/string_philosophies_char_arrays_stdstring_and/

Hope that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...