NSString简单细说(二)—— NSString的初始化

版本修改记录

版本号 修改时间
V1.0 2017.04.01

前言

前篇对NSString在API的框架中进行了整体的把握和了解,可以点击NSString简单细说(一)链接过去,但是在使用的时候还是要看细节,所以接下来几篇就会着眼于细节,重点讲述NSString的使用。感兴趣的可以看我上面几篇。
1. NSString简单细说(一)—— NSString整体架构

NSString的初始化

NSString的初始化方法一共有21个,下面就细说这些方法的使用。

一、+ (instancetype)string;方法

上代码

    // 1. + (instancetype)string;
    NSString *str = [NSString string];
    NSLog(@"str----%@",str);

看结果

// An empty string.
2017-04-03 11:27:29.749 NSString你会用吗?[1563:49138] str----

结论:该方法返回的字符串返回的是空的字符串。


二、- (instancetype)init;方法

上代码

    // 2. - (instancetype)init;
    //An initialized NSString object that contains no characters. The returned object may be different from the original receiver.
    NSString *str = [[NSString alloc] init];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 11:37:46.633 NSString你会用吗?[1708:57507] str----0x10a9a08b0----

结论:该方法返回的是空的字符串。


三、- (instancetype)initWithBytes:(const void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding;方法

上代码

    /**
    *3. - (instancetype)initWithBytes:(const void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding;
    *
    *  @param bytes :A buffer of bytes interpreted in the encoding specified by encoding.
    *  @param length :The number of bytes to use from bytes.
    *  @param encoding :The character encoding applied to bytes
    *
    *  @return :If the length of the byte string is greater than the specified length a nil value is returned.
    */
    
    NSUInteger length = 4;
    const void *bytes = "aabbccdd";
    NSString *str = [[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 20:33:37.401 NSString你会用吗?[3364:138958] str----0xa000000626261614----aabb

结论:可以看见length长度为4,当字符串长度大于length,则会截取的字符串;否则,则会输出全长度字符串。


四、- (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)freeBuffer;方法

上代码

    /**
     *4.- (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)freeBuffer;
     *
     *  @param bytes :A buffer of bytes interpreted in the encoding specified by encoding.
     *  @param length :The number of bytes to use from bytes.
     *  @param encoding :The character encoding applied to bytes
     *  @param freeBuffer :If YES, the receiver releases the memory with free() when it no longer needs the data; if NO it won’t.
     *
     *  @return :An initialized NSString object containing length bytes from bytes interpreted using the encoding encoding. The returned object may be different from the original receiver.
     */
    NSUInteger length = 4;
    void *a = "aassddd";
    NSString *str = [[NSString alloc] initWithBytesNoCopy:a length:length encoding:NSUTF8StringEncoding freeWhenDone:NO];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 20:47:17.738 NSString你会用吗?[3550:150321] str----0xa000000737361614----aass

这里如果freeBuffer设置为YES,在不用就会释放。

 NSString *str = [[NSString alloc] initWithBytesNoCopy:a length:length encoding:NSUTF8StringEncoding freeWhenDone:YES];

看结果

NSString你会用吗?(3593,0x104a063c0) malloc: *** error for object 0x100cc5df9: pointer being freed was not allocated

结论:可以看见freeBuffer设置为YES后被释放了,就crash了。


五、- (instancetype)initWithCharacters:(const unichar *)characters length:(NSUInteger)length;方法

上代码

    /**
     *5. - (instancetype)initWithCharacters:(const unichar *)characters length:(NSUInteger)length;
     *
     *  @param characters :A C array of UTF-16 code units; the value must not be NULL.
     *          Important:Raises an exception if characters is NULL, even if length is 0.
     *  @param length :The number of characters to use from characters.
     *
     *  @return :An initialized NSString object containing length characters taken from characters. The returned object may be different from the original receiver.
     */
    NSUInteger length = 4;
    const unichar *a = "zzzzzzzz";
    NSString *str = [[NSString alloc] initWithCharacters:a length:length];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 21:39:40.830 NSString你会用吗?[4339:190158] str----0x6000000301a0----空空空空

结论:简单不多说了。


六、- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer;方法

看代码

    /**
     * 6. - (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer;
     *
     *  @param characters :A C array of UTF-16 code units.
     *  @param length :The number of characters to use from characters.
     *  @param freeBuffer :If YES, the receiver releases the memory with free() when it no longer needs the data; if NO it won’t.
     *
     *  @return :An initialized NSString object that contains length characters from characters. The returned object may be different from the original receiver.
     */
        NSUInteger length = 4;
        unichar *a = "zzzzzzzzzzzzzzzz";
        NSString *str = [[NSString alloc] initWithCharactersNoCopy:a length:length freeWhenDone:NO];
        NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 22:07:36.654 NSString你会用吗?[4637:206036] str----0x60800002fb20----空空空空

结论:简单不多说了。


七、- (instancetype)initWithString:(NSString *)aString;方法

看代码

    /**
     * 7. - (instancetype)initWithString:(NSString *)aString;
     *
     *  @param aString :The string from which to copy characters. This value must not be nil.
     *                  Important:Raises an NSInvalidArgumentException if aString is nil.
     *
     *  @return :An NSString object initialized by copying the characters from aString. The returned object may be different from the original receiver.
     */
    NSUInteger length = 4;
    NSString *a = @"zzzzzzzzzzzzzzzz";
    NSString *str = [[NSString alloc] initWithString:a];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 22:21:22.655 NSString你会用吗?[4777:213816] str----0x10c20b088----zzzzzzzzzzzzzzzz

结论:同上。


八、- (instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding;方法

看代码

    /**
     * 8. - (instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding;
     *
     *  @param nullTerminatedCString :A C array of characters. The array must end with a NULL character; intermediate NULL characters are not allowed.
     *  @param encoding :The encoding of nullTerminatedCString
     *
     *  @return :An NSString object initialized using the characters from nullTerminatedCString. The returned object may be different from the original receiver
     */
    NSUInteger length = 4;
    const char *a = "azzzzzzzzzzzzzzb";
    NSString *str = [[NSString alloc] initWithCString:a encoding:NSUTF8StringEncoding];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 23:28:23.072 NSString你会用吗?[5359:238906] str----0x6080002428b0----azzzzzzzzzzzzzzb

结论:同上。


九、- (instancetype)initWithUTF8String:(const char *)nullTerminatedCString;方法

    /**
     * 9.- (instancetype)initWithUTF8String:(const char *)nullTerminatedCString;
     *
     *  @param nullTerminatedCString :A NULL-terminated C array of bytes in UTF-8 encoding. This value must not be NULL. Important :Raises an exception if bytes is NULL.
     *
     *  @return :An NSString object initialized by copying the bytes from bytes. The returned object may be different from the original receiver.
     */
    const char *a = "azzzzzzzzzzzzzzb";
    NSString *str = [[NSString alloc] initWithUTF8String:a];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 23:37:19.728 NSString你会用吗?[5466:246577] str----0x60000005de50----azzzzzzzzzzzzzzb

结论:同上。


十、- (instancetype)initWithFormat:(NSString *)format, ...;方法

    /**
     * 10.- (instancetype)initWithFormat:(NSString *)format, ...;
     *
     *  @param format :A format string.This value must not be nil. 
          Important :Raises an NSInvalidArgumentException if format is nil.
     *  @param ... :A comma-separated list of arguments to substitute into format.
          Important: When working with text that’s presented to the user, use the localizedStringWithFormat: method, or the initWithFormat:locale: or initWithFormat:locale:arguments: method, passing currentLocale as the locale.
     *
     *  @return :An NSString object initialized by using format as a template into which the remaining argument values are substituted according to the system locale. The returned object may be different from the original receiver.
     */
    NSString *str = [NSString stringWithFormat:@"AAA"];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-03 23:46:49.096 NSString你会用吗?[5567:253709] str----0xa000000004141413----AAA

结论:简单不解释。


十一、- (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argList;方法

上代码

    /**
     * 11.- (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argList;
     *
     *  @param format :A format string.This value must not be nil.
           Important :Raises an NSInvalidArgumentException if format is nil.
     *  @param argList :A list of arguments to substitute into format.
           Important: When working with text that’s presented to the user, use the localizedStringWithFormat: method, or the initWithFormat:locale: or initWithFormat:locale:arguments: method, passing currentLocale as the locale.
     *
     *  @return :An NSString object initialized by using format as a template into which the values in argList are substituted according to the current locale. The returned object may be different from the original receiver.
     */

     [self list:@"AAA",@"BBB",@"CCC",nil];

- (void)list:(NSString *)string,...{
    va_list argsList;
    va_start(argsList, string);
    if (string) {
        //输出第一个字符串
        NSLog(@"%@",string);
        NSString *otherString;
        while (1) {
            //依次取得所有参数
            otherString = va_arg(argsList, NSString*);
            if (otherString == nil) {
                break;
            }
            else {
                otherString = [[NSString alloc] initWithFormat:otherString arguments:argsList];
                NSLog(@"otherString---%@",otherString);
            }
        }
        
    }
    va_end(argsList);
}

看结果

2017-04-05 23:35:11.651 NSString你会用吗?[1648:49185] AAA
2017-04-05 23:35:11.651 NSString你会用吗?[1648:49185] otherString---BBB
2017-04-05 23:35:11.652 NSString你会用吗?[1648:49185] otherString---CCC

结论:直接读代码吧。


十二、- (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...;方法

看代码

    /**
     * 12.- (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...;     
     *
     *  @param format :A format string.This value must not be nil.
     Important :Raises an NSInvalidArgumentException if format is nil.
     *  @param locale An NSLocale object specifying the locale to use. To use the current locale, pass [NSLocale currentLocale]. To use the system locale, pass nil.For legacy support, this may be an instance of NSDictionary containing locale information.
     *  @param ... :A comma-separated list of arguments to substitute into format.
     *
     *  @return :Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale.
     */
    NSString *str = [[NSString alloc] initWithFormat:@"AAA" locale:nil];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-04 16:31:19.671 NSString你会用吗?[3788:157995] str----0xa000000004141413----AAA

结论:简单不解释。


十三、- (instancetype)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argList;方法

上代码

    /**
     * 13.- (instancetype)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argList; 
     *
     *  @param format :A format string.This value must not be nil.
     Important :Raises an NSInvalidArgumentException if format is nil.
     *  @param locale An NSLocale object specifying the locale to use. To use the current locale, pass [NSLocale currentLocale]. To use the system locale, pass nil.For legacy support, this may be an instance of NSDictionary containing locale information.
     *  @param argList :A list of arguments to substitute into format.
     *
     *  @return :An NSString object initialized by using format as a template into which values in argList are substituted according the locale information in locale. The returned object may be different from the original receiver.
     */
    [self list:@"AAA",@"BBB",@"CCC",nil];

- (void)list:(NSString *)string,...{
    va_list argsList;
    va_start(argsList, string);
    if (string) {
        //输出第一个字符串
        NSLog(@"%@",string);
        NSString *otherString;
        while (1) {
            //依次取得所有参数
            otherString = va_arg(argsList, NSString*);
            if (otherString == nil) {
                break;
            }
            else {
                otherString = [[NSString alloc] initWithFormat:otherString locale:nil arguments:argsList];
                NSLog(@"otherString---%@",otherString);
            }
        }
        
    }
    va_end(argsList);
}

看结果

2017-04-05 23:43:26.918 NSString你会用吗?[1770:55214] AAA
2017-04-05 23:43:26.919 NSString你会用吗?[1770:55214] otherString---BBB
2017-04-05 23:43:26.919 NSString你会用吗?[1770:55214] otherString---CCC

结论:直接看代码吧。


十四、- (instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;方法

上代码

    /**
     * 14.- (instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;
     *
     *  @param data : An NSData object containing bytes in encoding and the default plain text format (that is, pure content with no attributes or other markups) for that encoding.
     *  @param encoding: The encoding used by data. For possible values, see NSStringEncoding.
     *
     *  @return :Returns an NSString object initialized by converting given data into UTF-16 code units using a given encoding.
     */
    const void *dataStr = "AAABBBCCC";
    NSData *data = [NSData dataWithBytes:dataStr length:6];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-04 18:01:04.676 NSString你会用吗?[4570:196034] str----0xa004242424141416----AAABBB

结论:简单不解释。


十五、+ (instancetype)stringWithFormat:(NSString *)format, ...;方法

上代码

    /**
     * 15. + (instancetype)stringWithFormat:(NSString *)format, ...;
     *
     *  @param format : A format string.This value must not be nil.
          Important :Raises an NSInvalidArgumentException if format is nil.     
     *  @param ...: A comma-separated list of arguments to substitute into format.
     *
     *  @return :Returns a string created by using a given format string as a template into which the remaining argument values are substituted.
     */
    
    NSString *str = [NSString stringWithFormat:@"a=%@,b=%@",@"AAA",@"BBB"];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-04 18:25:16.133 NSString你会用吗?[4762:205925] str----0x60800022a600----a=AAA,b=BBB

结论:简单不解释。


十六、+ (instancetype)localizedStringWithFormat:(NSString *)format, ...;方法

上代码

    /**
     * 16. + (instancetype)localizedStringWithFormat:(NSString *)format, ...;
     *
     *  @param format : A format string.This value must not be nil.
     Important :Raises an NSInvalidArgumentException if format is nil.
     *  @param ...: A comma-separated list of arguments to substitute into format.
     *
     *  @return :A string created by using format as a template into which the following argument values are substituted according to the formatting information in the current locale.
     */
    
    NSString *str = [NSString localizedStringWithFormat:@"a=%@,b=%@",@"AAA",@"BBB"];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-04 18:34:00.899 NSString你会用吗?[4906:212813] str----0x600000030b80----a=AAA,b=BBB

结论:简单不解释。


十七、+ (NSString *)localizedUserNotificationStringForKey:(NSString *)key arguments:(NSArray *)arguments;方法

看代码

    /**
     * 17. + (NSString *)localizedUserNotificationStringForKey:(NSString *)key arguments:(NSArray *)arguments
     *
     *  @param key : The key to use when looking up the string in the app’s Localizable.strings file.
     *  @param arguments: An array of values to substitute for escaped characters in the string.
     *
     *  @return :Returns a localized string intended for display in a notification alert.
     */

我找到一段这样的代码

UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:@"Hello 5 seconds!" arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body" arguments:nil];                                             
content.subtitle = [NSString localizedUserNotificationStringForKey:@"good day" arguments:nil];
content.sound = [UNNotificationSound defaultSound];

注意这里key为 in the app’s Localizable.strings file。arguments可以传nil。

结论:这里要注意Localizable.strings file。


十八、+ (instancetype)stringWithCharacters:(const unichar *)characters length:(NSUInteger)length;方法

上代码

    /**
     * 18. + (instancetype)stringWithCharacters:(const unichar *)characters length:(NSUInteger)length;
     *
     *  @param characters : A C array of UTF-16 code units; the value must not be NULL. Important: Raises an exception if chars is NULL, even if length is 0.
     *  @param length:The number of characters to use from chars.
     *
     *  @return :Returns a string containing a given number of characters taken from a given C array of UTF-16 code units.
     */
    const unichar *charStr = "zzzzzzzzzzzzzzzz";
    NSString *str = [NSString stringWithCharacters:charStr length:4];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-04 21:31:13.120 NSString你会用吗?[5835:261446] str----0x600000025840----空空空空

结论:简单不叙。


十九、+ (instancetype)stringWithString:(NSString *)string;方法

上代码

    /**
     * 19. + (instancetype)stringWithString:(NSString *)string;
     *
     *  @param string : The string from which to copy characters. This value must not be nil. Important: Raises an NSInvalidArgumentException if aString is nil.
     *
     *  @return :Returns a string created by copying the characters from another given string.
     */
    NSString *string = @"AABBCCDD";
    NSString *str = [NSString stringWithString:string];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-04 21:35:30.768 NSString你会用吗?[5900:265086] str----0x1084cf088----AABBCCDD

结论:简单不叙。


二十、+ (instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc方法

上代码

    /**
     * 20. + (instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc
     *
     *  @param cString : A C array of bytes. The array must end with a NULL byte; intermediate NULL bytes are not allowed.
     *  @param enc : The encoding of cString.
     *
     *  @return :Returns a string containing the bytes in a given C array, interpreted according to a given encoding.
     */
    const char *cString = "AABBCCDD";
    NSString *str = [NSString stringWithCString:cString encoding:NSUTF8StringEncoding];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-04 21:50:33.245 NSString你会用吗?[6091:275251] str----0xa00cb2bef6db8618----AABBCCDD

结论:简单不叙。


二十一、+ (instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;方法

上代码

    /**
     * 21. + (instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;
     *
     *  @param nullTerminatedCString : A NULL-terminated C array of bytes in UTF8 encoding. Important:  Raises an exception if bytes is NULL.
     *
     *  @return :Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
     */
    const char *cString = "AABBCCDD";
    NSString *str = [NSString stringWithUTF8String:cString];
    NSLog(@"str----%p----%@",str,str);

看结果

2017-04-04 22:01:30.234 NSString你会用吗?[6258:283006] str----0xa00cb2bef6db8618----AABBCCDD

结论:简单不叙。


致谢

谢谢大家对我的关注,未完,待续~~~,我是刀客传奇,我是一个小码农。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容