当前位置:网站首页>[oc foundation framework] - < copy object copy >
[oc foundation framework] - < copy object copy >
2022-07-06 08:58:00 【About Xiaosi】
List of articles
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



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;
}

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

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: 0We 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

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

- 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
边栏推荐
- Pytorch view tensor memory size
- LeetCode:162. Looking for peak
- Leetcode: Sword finger offer 42 Maximum sum of continuous subarrays
- Marathon envs project environment configuration (strengthen learning and imitate reference actions)
- Advanced Computer Network Review(5)——COPE
- KDD 2022论文合集(持续更新中)
- LeetCode:387. The first unique character in the string
- LeetCode:236. The nearest common ancestor of binary tree
- 一改测试步骤代码就全写 为什么不试试用 Yaml实现数据驱动?
- Detailed explanation of dynamic planning
猜你喜欢

什么是MySQL?MySql的学习之路是怎样的

Advanced Computer Network Review(3)——BBR

JVM quick start
![[MySQL] limit implements paging](/img/94/2e84a3878e10636460aa0fe0adef67.jpg)
[MySQL] limit implements paging

Mise en œuvre de la quantification post - formation du bminf

704 binary search

Advanced Computer Network Review(4)——Congestion Control of MPTCP

LeetCode:124. 二叉树中的最大路径和

Mongodb installation and basic operation

Advanced Computer Network Review(5)——COPE
随机推荐
Tcp/ip protocol
Variable length parameter
使用标签模板解决用户恶意输入的问题
Super efficient! The secret of swagger Yapi
Warning in install. packages : package ‘RGtk2’ is not available for this version of R
LeetCode:124. 二叉树中的最大路径和
LeetCode:221. 最大正方形
LeetCode:214. 最短回文串
LeetCode:498. Diagonal traversal
Unsupported operation exception
力扣每日一题(二)
@Jsonbackreference and @jsonmanagedreference (solve infinite recursion caused by bidirectional references in objects)
Esp8266-rtos IOT development
Ijcai2022 collection of papers (continuously updated)
Computer graduation design PHP Zhiduo online learning platform
A convolution substitution of attention mechanism
LeetCode:41. 缺失的第一个正数
R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
注意力机制的一种卷积替代方式
可变长参数