iOS 內存管理(strong weak copy)詳解

(一)strong 強引用:一般使用strong  計數器+1,相當於非arc的 retain

(二)weak  弱引用:循環引用時使用(代理、block),相當於非arc的 assign

strong型指針就像是栓住的狗。

weak型指針就像是一個小孩指着狗喊到:“看!一隻狗在那” 

只要狗一直被栓着,小孩就能看到狗,(weak指針)會一直指向它。只要狗的牽繩脫落,狗就會跑掉,不管有多少小孩在看着它。

只要最後一個strong型指針不再指向對象,那麼對象就會被釋放,同時所有的weak型指針都將會被清除。

(三)copy :改變副本的時候不改變源對象

1、遵從 nscopying 、nsmutablecopying協議

2、深拷貝(對象拷貝,內容拷貝):新對象計數器置1 原對象計數器不變


   eg1:

 NSString *str = [[NSString alloc]initWithFormat:@"123"]; 
    NSMutableString *strcopy = [str mutableCopy];
    [strcopy appendFormat:@"456"];
    NSLog(@"str=%@",str);
    NSLog(@"strcopy=%@",strcopy);

   2015-10-21 16:40:43.350 ceshi[1149:95383] str=123

   2015-10-21 16:40:43.351 ceshi[1149:95383] strcopy=123456


  eg2:

NSMutableString *str = [[NSMutableString alloc]initWithFormat:@"123"];
    NSString *strcopy = [str copy];
    NSLog(@"str=%@",str);
    NSLog(@"strcopy=%@",strcopy);

   2015-10-21 16:42:58.409 ceshi[1181:96946] str=123

   2015-10-21 16:42:58.409 ceshi[1181:96946] strcopy=123


  eg3:

NSMutableString *str = [[NSMutableString alloc]initWithFormat:@"123"];
    NSMutableString *strcopy = [str mutableCopy];
    [strcopy appendFormat:@"456"];
    NSLog(@"str=%@",str);
    NSLog(@"strcopy=%@",strcopy);

   2015-10-21 16:41:59.342 ceshi[1170:96326] str=123

   2015-10-21 16:41:59.342 ceshi[1170:96326] strcopy=123456



3、淺拷貝(指針拷貝、地址拷貝):源對象計數器+1 相當於retain strong

只有一種情況是淺拷貝:不可變對象調用copy

  eg1:

NSString *str = [[NSString alloc]initWithFormat:@"123"];
    NSString *strcopy = [str copy];
    [str stringByAppendingString:@"11"];


如有錯誤請批評指正 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章