当前位置:网站首页>[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
边栏推荐
- UML diagram memory skills
- What is an R-value reference and what is the difference between it and an l-value?
- vb. Net changes with the window, scales the size of the control and maintains its relative position
- Nacos 的安装与服务的注册
- 数字人主播618手语带货,便捷2780万名听障人士
- Advance Computer Network Review(1)——FatTree
- UnsupportedOperationException异常
- 超高效!Swagger-Yapi的秘密
- Leetcode: Jianzhi offer 04 Search in two-dimensional array
- LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置
猜你喜欢
Advanced Computer Network Review(3)——BBR
Charging interface docking tutorial of enterprise and micro service provider platform
Delay initialization and sealing classes
LeetCode:221. Largest Square
[OC-Foundation框架]---【集合数组】
IJCAI2022论文合集(持续更新中)
UnsupportedOperationException异常
Mise en œuvre de la quantification post - formation du bminf
Nacos 的安装与服务的注册
UML图记忆技巧
随机推荐
Revit secondary development Hof method calls transaction
Marathon envs project environment configuration (strengthen learning and imitate reference actions)
UML圖記憶技巧
可变长参数
Li Kou daily question 1 (2)
vb. Net changes with the window, scales the size of the control and maintains its relative position
To effectively improve the quality of software products, find a third-party software evaluation organization
LeetCode:394. String decoding
Chapter 1 :Application of Artificial intelligence in Drug Design:Opportunity and Challenges
Current situation and trend of character animation
CUDA implementation of self defined convolution attention operator
LeetCode:387. 字符串中的第一个唯一字符
LeetCode:221. Largest Square
ant-design的走马灯(Carousel)组件在TS(typescript)环境中调用prev以及next方法
[OC-Foundation框架]---【集合数组】
[today in history] February 13: the father of transistors was born The 20th anniversary of net; Agile software development manifesto was born
使用latex导出IEEE文献格式
Hutool gracefully parses URL links and obtains parameters
如何正确截取字符串(例:应用报错信息截取入库操作)
【文本生成】论文合集推荐丨 斯坦福研究者引入时间控制方法 长文本生成更流畅