当前位置:网站首页>[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
边栏推荐
- 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
- Li Kou daily question 1 (2)
- Revit 二次开发 HOF 方式调用transaction
- MongoDB 的安装和基本操作
- Ijcai2022 collection of papers (continuously updated)
- LeetCode:236. The nearest common ancestor of binary tree
- LeetCode41——First Missing Positive——hashing in place & swap
- LeetCode:41. Missing first positive number
- How to effectively conduct automated testing?
- R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
猜你喜欢
可变长参数
BMINF的后训练量化实现
Chapter 1 :Application of Artificial intelligence in Drug Design:Opportunity and Challenges
[OC-Foundation框架]---【集合数组】
数学建模2004B题(输电问题)
Delay initialization and sealing classes
[OC-Foundation框架]--<Copy对象复制>
ROS compilation calls the third-party dynamic library (xxx.so)
[embedded] cortex m4f DSP Library
Advanced Computer Network Review(4)——Congestion Control of MPTCP
随机推荐
[OC]-<UI入门>--常用控件的学习
LeetCode:214. Shortest palindrome string
Advance Computer Network Review(1)——FatTree
Current situation and trend of character animation
【剑指offer】序列化二叉树
甘肃旅游产品预订增四倍:“绿马”走红,甘肃博物馆周边民宿一房难求
Ijcai2022 collection of papers (continuously updated)
Simple use of promise in uniapp
requests的深入刨析及封装调用
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
LeetCode:836. Rectangle overlap
SimCLR:NLP中的对比学习
可变长参数
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
Charging interface docking tutorial of enterprise and micro service provider platform
Marathon envs project environment configuration (strengthen learning and imitate reference actions)
LeetCode:673. Number of longest increasing subsequences
Leetcode: Jianzhi offer 03 Duplicate numbers in array
Leetcode刷题题解2.1.1
Using C language to complete a simple calculator (function pointer array and callback function)