当前位置:网站首页>[oc foundation framework] - < copy object copy >

[oc foundation framework] - < copy object copy >

2022-07-06 08:58:00 About Xiaosi

copy And mutableCopy Method

copy Method

copy Method is used to copy a copy of an object ,copy Methods always return an unmodifiable copy of the object , Even if the object itself is modifiable

  • for example :NSMutableString Of copy Method Returns a string object that cannot be modified

mutableCopy Method

  • mutableCopy Method is used to copy a mutable copy of an object , Generally speaking ,mutableCopy Method returns a modifiable copy of the object , Even if the copied object is not modifiable

mutableCopy Method copy Common characteristics of methods

in any case copy and mutableCopy Always return a copy of the object , When the program makes modifications to the replicated copy , The original object is usually not affected

mutableCopy and copy Program instance

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    
    @autoreleasepool {
    
        NSMutableString *book = [NSMutableString stringWithString:@" insane iOS lebron "];
        NSMutableString *bookCopy = [book mutableCopy];
        [bookCopy replaceCharactersInRange:
            NSMakeRange (2, 3)
            withString:@"Android"];
        NSLog(@"book  Value :%@", book);
        //  The copy of the string has changed 
        NSLog(@" bookCopy Value   by  %@", bookCopy);


        NSString *str = @"fkiOS";
        //  assignment str( A copy of an immutable substring  -- variable )
        NSMutableString * strCopy = [str mutableCopy];
        // Append characters to variable 
        [strCopy appendString:@" ,org"];
        NSLog(@"%@ ", strCopy);


        // call book Of Copy Method returns an unmodifiable copy ·
        NSMutableString* bookCopy2 = [book copy];
        //  Cannot be modified. An error occurred 
        //Thread 1: "Attempt to mutate immutable object with appendString:"
        // notes 
// [bookCopy2 appendString:@"123456"];

    }
    return 0;
}` Insert a code chip here `
  • When calling a method to return an unmodifiable copy
 // call book Of Copy Method returns an unmodifiable copy ·
        NSMutableString* bookCopy2 = [book copy];
        //  Cannot be modified. An error occurred 
        //Thread 1: "Attempt to mutate immutable object with appendString:"
        // notes 
// [bookCopy2 appendString:@"123456"];

  • In the above procedure , although str It's an immutable string But by mutableCopy The method still gets a variable copy , So it's OK to strCopy Make changes
  • although book Is a variable string but calls copy An immutable copy of what you send So right. bookCopy2 Modify the string Can cause errors

NScopying And NSmutableCopying agreement

adopt copy And mutableCopy Method copies the copy of the object, which is very convenient to open
But whether custom classes can be substituted copy And mutableCopy Methods to replicate ?

OC Regulations

  • Xcode Of It can be seen from the error report although NSObject Provides copy and mutablecopy Method But a custom class cannot call these two methods to copy itself

 Insert picture description here

 Insert picture description here

 Insert picture description here

This detail will not be repeated

Deep copy and light copy

A shallow copy

Let's take a simple example of class replication
Define a FKdog object

Note that the protocol is declared in the interface section NSCopying

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface FKdog : NSObject  <NSCopying> // Statement copy agreement   Because it's a class 
@property (nonatomic, strong) NSMutableString* name;
@property (nonatomic, assign) int age;
@end

NS_ASSUME_NONNULL_END

The implementation part of shallow replication

- (id)copyWithZone:(nullable NSZone *)zone {
    
    FKdog* dog = [[[self class] allocWithZone:zone] init];
    dog.name = self.name; // Pay attention to differences 
    dog.age = self.age;
    return dog;
}
#import <Foundation/Foundation.h>
#import "FKdog.h"

int main(int argc, const char * argv[]) {
    
    @autoreleasepool {
    
        FKdog *d1 = [[FKdog alloc] init];
        d1.name = [NSMutableString stringWithString:@" Wangcai "];
        d1.age = 20;
        FKdog *d2 = [d1 copy];
        [d2.name replaceCharactersInRange:NSMakeRange(0, 2) withString:@" Wangcai 2 Number "];
        NSLog(@"%@, %d", d1.name, d1.age);
        NSLog(@"%@, %d", d2.name, d2.age);
    }
    return 0;
}

 Insert picture description here

About shallow replication

Called above dog1 Of copy Method copies a copy , And copy the copy dog2 Variable , Next, I modified dog2 Of name attribute Output

  • Found that we just modified dog2 Of name But why dog1 It's changed too

  •  Insert picture description here

  • Be careful ,name Is a variable of type pointer , The address of the string stored in this variable , Not the string itself , The effect of this assignment is dog Of name Attributes and copied objects self Of name Property points to the same string and age Variables are not difficult to change dog1 Will not change

  • ( We put dog2 Change your age to 100 Find out dog1 still 20) as follows

  • 2022-05-25 19:19:55.815766+0800 OC-copy[15837:2289009] Wangcai 2 Number , 20 2022-05-25 19:19:55.815971+0800 OC-copy[15837:2289009] Wangcai 2 Number , 100 Program ended with exit code: 0

  • We can come to a conclusion As long as it is a shallow copy As long as it is Pointer types Properties of

  • Changing one will change the other The attribute value

  •  Insert picture description here

Deep copy

Deep replication takes a different approach Divine replication not only copies the object itself , It also recursively copies the attributes of each pointer type Until the two objects have no common parts Will implement NSCopy The modification of the protocol can realize deep replication

Shallow copy to deep copy

#import "FKdog.h"

@implementation FKdog

- (id)copyWithZone:(nullable NSZone *)zone {
    
    FKdog* dog = [[[self class] allocWithZone:zone] init];
    dog.name = [self.name mutableCopy];
    // Modify the following in the pointer type variable self Plus 
    //mutableCopy
    dog.age = self.age;
    return dog;
}

@end

 Insert picture description here

  • You can see dog1 Pointer type of name Don't change

About deep replication

  • There is no simple object to be copied in the above program name Attribute value assigned to the new object name attribute , Instead, the original object's name The attribute value makes a variable copy , Then assign the value of the variable copy to the new object name attribute .
    This ensures the original FKDog Object and new FKDog There is no common part of the question of objects , This enables deep replication .

  • When FKDog After deep replication , Compile again 、 Run the top Program , You will see two FKDog The question of the object has no relevance , When one FKDog Object's name When the attribute value changes , the other one FKDog Object's name Attribute values are not affected

     Foundation  Most of the classes in the framework only implement shallow replication .
    

Additional knowledge increases

For our shallow replication Protocol implementation code

- (id)copyWithZone:(nullable NSZone *)zone {
    
    FKdog* dog = [[[self class] allocWithZone:zone] init];
    dog.name = self.name; // Pay attention to differences 
    dog.age = self.age;
    return dog;
}

#import <Foundation/Foundation.h>
#import "FKdog.h"

int main(int argc, const char * argv[]) {
    
    @autoreleasepool {
    
        FKdog *d1 = [[FKdog alloc] init];
        d1.name = [NSMutableString stringWithString:@" Wangcai "];
        d1.age = 20;
        FKdog *d2 = [d1 copy];
        [d2.name replaceCharactersInRange:NSMakeRange(0, 2) withString:@" Wangcai 2 Number "];
        NSLog(@"%@, %d", d1.name, d1.age);
        NSLog(@"%@, %d", d2.name, d2.age);
    }
    return 0;
}

Notice that we are giving dog2 When you assign It's using copy Method, but at this time copy It has not become variable copy Why? dog2 Of name Can also be What about change ?

- because We're writing NSCopying When the agreement is made, it is directly equal to the symbol It is equivalent to that we rewrite it internally copy The method is like this copy The method will change
If the method is like this

   dog.name = [self.name copy]; // Pay attention to differences 

Then the system will prompt dog2 Data that cannot be modified

原网站

版权声明
本文为[About Xiaosi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060850139158.html