Objective-C文法之copy和mutablecopy

來源:互聯網
上載者:User

標籤:

#pragma mark 示範字串的copy//深拷貝--對象拷貝--內容拷貝(產生新對象)新對象計數器+1,原對象不變void stringmutableCopy(){    //string = 1    NSString *string = [[NSString alloc]initWithFormat:@"age is %i", 10];    //str = 1    //產生了一個新對象,原對象的計數器不變    NSMutableString *str = [string mutableCopy];    NSLog(@"str:%zi",[string retainCount]);    NSLog(@"string:%zi",[str retainCount]);        //修改副本,原對象不變    [str appendString:@"abcd"];    NSLog(@"string:%@",string);    NSLog(@"str:%@",str);            //string =0    [string release];    [str release];//copy也需要release}//不可變拷不可變--淺拷貝//淺拷貝--指標拷貝--地址拷貝 (拷貝指標,不會產生新的對象,返回原對象本身,原對象計數器+1)void stringcopy(){    NSString *string = [[NSString alloc]initWithFormat:@"age is %i", 10];    //為了效能著想,針對copy原則,string本來是不可變,[string copy]並沒有產生一個新的對象,而是返回對象本身,copy相當與retain    NSString *str = [string copy];//產生一個不可變對象    //NSLog(@"%i", string == str);//結果為1,copy出來的對象為同一個    NSLog(@"%zi",[string retainCount]);    NSLog(@"%zi",[str retainCount]);        [string release];    [str release];//使用copy或者mutablecopy都需要release}#pragma mark 可變字串的copy//深拷貝void mutableStringCopy(){        NSMutableString *string = [NSMutableString stringWithFormat:@"age is %i",10];        NSString *str = [string copy];//產生一個不可變的str        [str release];}//深拷貝void mutableStringmutableCopy(){    NSMutableString *string = [NSMutableString stringWithFormat:@"age is %i",10];    //會產生一個新的對象    NSMutableString *str = [string mutableCopy];    [str appendString:@"1234"];    NSLog(@"str:%@",str);    NSLog(@"string%@",string);    [str release];    }

 

Objective-C文法之copy和mutablecopy

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.