• IOS NSString与NSMutableString区别详解


    指针变量和实际对象

     

    Immutable strings

     

    //  Setup  two  variables  to  point  to  the  same  string 
    NSString * str1 = @"Hello World"; 
    NSString * str2 = str1; 

    //  "Replace"  the  second  string 
    str2 = @"Hello ikilimnik"; 

    //  And  list  their  current  values 
    NSLog(@"str1 = %@, str2 = %@", str1, str2); 

     

    output:str1 = Hello World, str2 = Hello ikilimnik 



    Mutable strings 

    //  Setup  two  variables  to  point  to  the  same  string 
    NSMutableString * str1 = [NSMutableString stringWithString:@"Hello World"]; 
    NSMutableString * str2 = str1; 

    //  "Replace"  the  second  string 
    [str2 setString:@"Hello ikilimnik"]; 

    //  And  list  their  current  values 
    NSLog(@"str1 = %@, str2 = %@", str1, str2); 

     

    output:str1 = Hello ikilimnik, str2 = Hello ikilimnik 

     

    注意,当你使用不可变的NSString class时,替换旧的字符串的唯一方式就是创建一个新的字符串然后更新你的变量“str2”

    来指向这个新的字符串。这个操作不会影响“str1”所指向的内容,因此它将继续指向初始的字符串。

     

    在NSMutableString的例子里,我们没有创建第二个字符串,而是通过改变已经存在的可变字符串“str2”的内容来代替。

    由于str1和str2两个变量都仍然指向同一个字符串对象,从nslog中可以看到它们值都将会被更新。

     

    理解指针变量和它实际指向对象的不同是非常重要的。一个NSString对象是不可变的,但是这并不阻止你改变指向这个不

    可变对象的指针的值。

     

    "NSString *"这个数据类型代表一个NSString对象的指针,不是NSString对象本身。

    "NSMutableString *"这个数据类型则是代表"NSMutableString"对象本身,这两者是有区别的。

     

    这也是有的时候我们使用NSMutableString类型字符串时,要使用copy的原因,因为可能不想改变新的字符串时影响到旧的字符串的值。

    如:

    NSMutableString * str2 = [str1 mutableCopy]; 

    p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo}

  • 相关阅读:
    python线程详解
    Beego框架在模板中使用自定义函数
    golang打印英文格式时间日期
    如何让SQL语句不执行默认排序,而是按照in语句的顺序返回结果
    Git clone 报错 Unable to negotiate with xxx.xxx.xxx.xxx port 12345: no matching cipher found. Their offer: aes128-cbc,3des-cbc,blowfish-cbc
    Mysql去掉html标签函数
    Nodejs的npm安装模块时候报错:npm ERR! Error: CERT_UNTRUSTED的解决方法
    树莓派使用DHT11温湿度传感器
    ubuntu源列表(清华,阿里,官方,选一即可)
    将tgz文件解压到指定目录
  • 原文地址:https://www.cnblogs.com/hopeanCom/p/2746045.html
Copyright © 2020-2023  润新知