Copy and mutableCopy

  • The purpose of copy: to create a copy object, independent of the source object
    • The source object has been modified without affecting the replica object
    • The replica object is modified without affecting the source object
    • NSString, NSArray, and NSDictionary have copy functions.
  • IOS provides two copy methods
    • 1. Copy, an immutable copy
    • 2. MutableCopy. Creates mutableCopy
  • Deep copy and shallow copy
    • 1. Deep copy: Copy content to generate new objects
    • 2. Shallow copy: the pointer is copied and no new object is generated
  • Immutable strings use immutable copy, because the content is immutable and there is no mutable operation, it is copied directly without creating a new object.

  • Mutable content uses immutable copy, and immutable content uses mutable copy, which is content copy, creating new objects.

  • Ask yourself if there is a problem with the following code
@property (copy, nonatomic) NSMutableArray *data;
MJPerson *p = [[MJPerson alloc] init];
p.data = [NSMutableArray array];
[p.data addObject:@"jack"];
[p.data addObject:@"rose"];
[p release];
Copy the code
  • The answer is that there is a problem with saying there is no add method

  • The essence of the copy method is this old count minus 1, the new count plus 1. Mutable content uses immutable copy, creates a new immutable object, NSArray, so there’s no method for that

  • There is no mutableCopy strategy. So I’ll stick with strong.

Custom copy

  • demand
    • 1. There is a data model, many of which have completed the assignment, jump to the next page, process data and return, I want some value difference in the data. You can consider custom copy
  • Abide by the agreement
  • Rewrite the copyWithZone method
#import <Foundation/Foundation.h>

@interface MJPerson : NSObject <NSCopying>
@property (assign, nonatomic) int age;
@property (assign, nonatomic) double weight;
@end

#import "MJPerson.h"

@implementation MJPerson

- (id)copyWithZone:(NSZone *)zone
{
    MJPerson *person = [[MJPerson allocWithZone:zone] init];
    person.age = self.age;
//    person.weight = self.weight;
    return person;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"age = %d, weight = %f", self.age, self.weight];
}

@end


        MJPerson *p1 = [[MJPerson alloc] init];
        p1.age = 20;
        p1.weight = 50;

        MJPerson *p2 = [p1 copy];
//        p2.age = 30;

        NSLog(@"%@", p1);
        NSLog(@"%@", p2);

Copy the code