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

版本修改记录

版本号修改时间
V1.02017.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

结论:简单不叙。


致谢

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



作者:刀客传奇
链接:https://www.jianshu.com/p/da9cd196e1dd
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值