天天看點

object-c 深複制和淺複制

在ObjC中,什麼是深淺拷貝?

深淺拷貝分别指深拷貝和淺拷貝,即mutableCopy和copy方法。

copy複制一個不可變對象,而mutableCopy複制一個mutable可變對象。

什麼時候用到深淺拷貝?下面舉幾個例子說明。

非容器類對象

如NSString,NSNumber等一類對象

示例1:

1

2

3

4

5

     // 非容器類對象

     NSString  *str  =  @ "origin string";

     NSString  *strCopy  =  [str copy ];

     NSMutableString  *mstrCopy  =  [str mutableCopy ];

     [mstrCopy appendString : @ "??" ];

檢視記憶體可以發現,str和strCopy指向的是同一塊記憶體區域,我們稱之為弱引用(weak reference)。而mstrCopy是真正的複制,系統為其配置設定了新記憶體空間,儲存從str複制過來的字元串值。從最後一行代碼中修改這些值而不影 響str和strCopy中可證明。

示例2:

1

2

3

4

5

6

7

     NSMutableString  *mstr  =  [ NSMutableString stringWithString : @ "origin" ];

     NSString  *strCopy  =  [mstr copy ];

     NSMutableString  *mstrCopy  =  [mstr copy ];

     NSMutableString  *mstrMCopy  =  [mstr mutableCopy ];

     //[mstrCopy appendString:@"1111"];  //error

     [mstr appendString : @ "222" ];

     [mstrMCopy appendString : @ "333" ];

以上四個對象所配置設定的記憶體都是不一樣的。而且對于mstrCopy,它所指向的其實是一個imutable對象,是不可改變的,是以會出錯。這點要注意,好好了解。

小結:

對于非容器類對象,有:

  • 如果對一個不可變對象複制,copy是指針複制,即淺拷貝;而mutableCopy則是對象複制,即深拷貝。(示例1)
  • 如果是對可變對象複制,都是深拷貝,但copy複制傳回的對象是不可變的。(示例2)

容器類對象深淺複制

比如NSArray,NSDictionary等。對于容器類本身,上面讨論的結論也适用的,下面探讨的是複制後容器内對象的變化。

示例3

1

2

3

4

5

6

7

8

9

10

11

12

     NSArray  *array1      =  [ NSArray arrayWithObjects : @ "a", @ "b", @ "c", nil ];

     NSArray  *arrayCopy1  =  [array1 copy ];

     //arrayCopy1是和array同一個NSArray對象(指向相同的對象),包括array裡面的元素也是指向相同的指針

    NSLog ( @ "array1 retain count: %d", [array1 retainCount ] );

    NSLog ( @ "array1 retain count: %d", [arrayCopy1 retainCount ] );

     NSMutableArray  *mArrayCopy1  =  [array1 mutableCopy ];

     //mArrayCopy1是array1的可變副本,指向的對象和array1不同,但是其中的元素和array1中的元素指向的還是同一個對象。mArrayCopy1還可以修改自己的對象

     [mArrayCopy1 addObject : @ "de" ];

     [mArrayCopy1 removeObjectAtIndex : 0 ];

array1和arrayCopy1是指針複制,而mArrayCopy1是對象複制,符合前面示例1讨論的結論。mArrayCopy1可以改變其内的元素:删除或添加。但容器内的元素内容都是淺拷貝。

示例4

1

2

3

4

5

6

7

8

9

10

11

12

13

     NSArray  *mArray1  =  [ NSArray arrayWithObjects : [ NSMutableStringstringWithString : @ "a" ], @ "b", @ "c", nil ];

    NSLog ( @ "mArray1 retain count: %d", [mArray1 retainCount ] );

     NSArray  *mArrayCopy2  =  [mArray1 copy ];

    NSLog ( @ "mArray1 retain count: %d", [mArray1 retainCount ] );

     // mArray1和mArrayCopy2指向同一對象,retain值+1。

     NSMutableArray  *mArrayMCopy1  =  [mArray1 mutableCopy ];

    NSLog ( @ "mArray1 retain count: %d", [mArray1 retainCount ] );

     //mArrayCopy2和mArray1指向的是不一樣的對象,但是其中的元素都是一樣的對象——同一個指針

     NSMutableString  *testString  =  [mArray1 objectAtIndex : 0 ];

     //testString = @"1a1";//這樣會改變testString的指針,其實是将@“1a1”臨時對象賦給了testString

     [testString appendString : @ " tail" ]; //這樣以上三個數組的首元素都被改變了

由此可見,對于容器而言,其元素對象始終是指針複制。如果需要元素對象也是對象複制,就需要實作深拷貝。http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Copying.html

示例5

1

2

3

4

     NSArray  *array  =  [ NSArray arrayWithObjects : [ NSMutableStringstringWithString : @ "first" ], [NSStringstringWithString : @ "b" ], @ "c", nil ];

     NSArray  *deepCopyArray = [ [ NSArray alloc ] initWithArray : array copyItems :  YES ];

     NSArray * trueDeepCopyArray  =  [ NSKeyedUnarchiver unarchiveObjectWithData :

     [ NSKeyedArchiver archivedDataWithRootObject : array ] ];

trueDeepCopyArray是完全意義上的深拷貝,而deepCopyArray則不是,對于deepCopyArray内的不可變元素其還是指針複制。

或者我們自己實作深拷貝的方法。因為如果容器的某一進制素是不可變的,那你複制完後該對象仍舊是不能改變的,是以隻需要指針複制即可。除非你對容器内的元素重新指派,否則指針複制即已足夠。

舉個例子,[[array objectAtIndex:0]appendstring:@”sd”]後其他的容器内對象并不會受影響。[[array objectAtIndex:1]和[[deepCopyArray objectAtIndex:0]盡管是指向同一塊記憶體,但是我們沒有辦法對其進行修改——因為它是不可改變的。是以指針複制已經足夠。是以這并不是完全 意義上的深拷貝。

自己實作深拷貝的方法

NSDictionaryMutableDeepCopy.h

1

2

3

4

5

6

7

8

#import <foundation /Foundation.h>

@interface  NSDictionary (MutableDeepCopy )

-  ( NSMutableDictionary  * )mutableDeepCopy;

@end

< /foundation>

NSDictionaryMutableDeepCopy.m

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

#import "NSDictionaryMutableDeepCopy.h"

@implementation  NSDictionary (MutableDeepCopy )

-  ( NSMutableDictionary  * )mutableDeepCopy  {

     NSMutableDictionary  *ret  =  [ [ NSMutableDictionary alloc ]

                                initWithCapacity : [self count ] ];

     NSArray  *keys  =  [self allKeys ];

     for  ( id key  in keys )  {

         id oneValue  =  [self valueForKey :key ];

         id oneCopy  =  nil;

         if  ( [oneValue respondsToSelector : @selector (mutableDeepCopy ) ] )  {

            oneCopy  =  [oneValue mutableDeepCopy ];

         }

         else  if  ( [oneValue respondsToSelector : @selector (mutableCopy ) ] )  {

            oneCopy  =  [oneValue mutableCopy ];

         }

         if  (oneCopy  ==  nil )  {

            oneCopy  =  [oneValue copy ];

         }

         [ret setValue :oneCopy forKey :key ];

     }

     return ret;

}

@end

使用類别方法來實作。

自定義對象

如果是我們定義的對象,那麼我們自己要實作NSCopying,NSMutableCopying這樣就能調用copy和mutablecopy了。舉個例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

5

@interface MyObj  : NSObject<nscopying ,NSMutableCopying>

{

          NSMutableString  *name;

          NSString  *imutableStr;

          int age;

}

@property  (nonatomic, retain )  NSMutableString  *name;

@property  (nonatomic, retain )  NSString  *imutableStr;

@property  (nonatomic )  int age;

@end

@implementation MyObj

@synthesize name;

@synthesize age;

@synthesize imutableStr;

-  ( id )init

{

          if  (self  =  [super init ] )

          {

                   self.name  =  [ [ NSMutableString alloc ]init ];

                   self.imutableStr  =  [ [ NSString alloc ]init ];

                   age  =  - 1;

          }

          return self;

}

-  ( void )dealloc

{

          [name release ];

          [imutableStr release ];

          [super dealloc ];

}

-  ( id )copyWithZone : ( NSZone  * )zone

{

         MyObj  *copy  =  [ [ [self class ] allocWithZone :zone ] init ];

         copy ->name  =  [name copy ];

         copy ->imutableStr  =  [imutableStr copy ];

//       copy->name = [name copyWithZone:zone];;

//       copy->imutableStr = [name copyWithZone:zone];//

         copy ->age  = age;

          return copy;

}

-  ( id )mutableCopyWithZone : ( NSZone  * )zone

{

         MyObj  *copy  = NSCopyObject (self,  0, zone );

         copy ->name  =  [self.name mutableCopy ];

         copy ->age  = age;

          return copy;

}

@end

< /nscopying

本文轉自: (轉)ObjectiveC 深淺拷貝學習