Strong, copy difference

Time:2022-5-11

Strong, how is copy different? Practice makes true knowledge! Upper code

strong

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong)NSString *name;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    Nsmutablestring * string = [[nsmutablestring alloc] initwithstring: @ "Zhang San"];
    self.name = string;
    Nslog (@ "string:% @, address:% P", string, string);
    Nslog (@ "self. Name:% @, address% P", self. Name, self. Name);
    [string appendString:@"1"];
    Nslog (@ "string:% @, address:% P", string, string);
    Nslog (@ "self. Name:% @, address% P", self. Name, self. Name);
}

@end

Operation results

2021-06-04 22:54:17.867578 + 0800 iosdemo [1557:53589] string: Zhang San, address: 0x6000008aecd0
2021-06-04 22:54:17.867716+0800 iOSDemo[1557:53589] self. Name: Zhang San, address 0x6000008aecd0
2021-06-04 22:54:17.867810 + 0800 iosdemo [1557:53589] string: Zhang San 1, address: 0x6000008aecd0
2021-06-04 22:54:17.867893+0800 iOSDemo[1557:53589] self. Name: Zhang San 1, address 0x6000008aecd0

copy

//
//  ViewController.m
//  iOSDemo
//
//Created by Peng Zhiyao on 2021 / 6 / 4
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,copy)NSString *name;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    Nsmutablestring * string = [[nsmutablestring alloc] initwithstring: @ "Zhang San"];
    self.name = string;
    Nslog (@ "string:% @, address:% P", string, string);
    Nslog (@ "self. Name:% @, address% P", self. Name, self. Name);
    [string appendString:@"1"];
    Nslog (@ "string:% @, address:% P", string, string);
    Nslog (@ "self. Name:% @, address% P", self. Name, self. Name);
    
}

@end

Operation results

2021-06-04 22:56:08.281057 + 0800 iosdemo [1582:54701] string: Zhang San, address: 0x6000008c5110
2021-06-04 22:56:08.281187+0800 iOSDemo[1582:54701] self. Name: Zhang San, address 0x6000006b6240
2021-06-04 22:56:08.281303 + 0800 iosdemo [1582:54701] string: Zhang San 1, address: 0x6000008c5110
2021-06-04 22:56:08.281394+0800 iOSDemo[1582:54701] self. Name: Zhang San, address 0x6000006b6240

analysis

  • When we assign values,strongIs to pass the address value directly to the attribute of the object, andcopyIs to open up a new space and assign values to the properties of the object.
  • NSStringCopy is recommended for attributes of type becauseNSMutableStringyesNSStringSubclass of, ifNSMutableStringObject of type assigned toNSStringWhen the object changes, the attribute value will change, soNSStringRecommended usecopymodification. (key points of interview)
  • The difference between deep copy and shallow copy is also reflected in the above. Shallow copy is the copy address and deep copy is the copy value.