当前位置:网站首页>[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: 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
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
边栏推荐
- [OC]-<UI入门>--常用控件-提示对话框 And 等待提示器(圈)
- Navicat premium create MySQL create stored procedure
- What is an R-value reference and what is the difference between it and an l-value?
- Digital people anchor 618 sign language with goods, convenient for 27.8 million people with hearing impairment
- What are the common processes of software stress testing? Professional software test reports issued by companies to share
- 在QWidget上实现窗口阻塞
- R language uses the principal function of psych package to perform principal component analysis on the specified data set. PCA performs data dimensionality reduction (input as correlation matrix), cus
- Problems encountered in connecting the database of the project and their solutions
- Detailed explanation of dynamic planning
- Variable length parameter
猜你喜欢
CUDA realizes focal_ loss
UML圖記憶技巧
Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
[text generation] recommended in the collection of papers - Stanford researchers introduce time control methods to make long text generation more smooth
Compétences en mémoire des graphiques UML
[OC-Foundation框架]---【集合数组】
CUDA implementation of self defined convolution attention operator
[OC]-<UI入门>--常用控件-提示对话框 And 等待提示器(圈)
Warning in install. packages : package ‘RGtk2’ is not available for this version of R
Detailed explanation of dynamic planning
随机推荐
LeetCode:劍指 Offer 42. 連續子數組的最大和
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Philosophical enlightenment from single point to distributed
LeetCode:214. 最短回文串
BN折叠及其量化
Ijcai2022 collection of papers (continuously updated)
Hutool gracefully parses URL links and obtains parameters
超高效!Swagger-Yapi的秘密
requests的深入刨析及封装调用
Navicat Premium 创建MySql 创建存储过程
LeetCode:34. Find the first and last positions of elements in a sorted array
vb. Net changes with the window, scales the size of the control and maintains its relative position
【嵌入式】Cortex M4F DSP库
LeetCode:394. 字符串解码
[sword finger offer] serialized binary tree
LeetCode:221. 最大正方形
Navicat premium create MySQL create stored procedure
Intel Distiller工具包-量化实现3
R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
LeetCode:836. 矩形重叠