iOS中的Copy

2018-09-21  本文已影响0人  皆为序幕_

copy的概念特点

NSString * str;
NSLog(@"str = %p, str = %p",str,&str);
str = @"demo";
NSMutableString *copyStr = [str copy];
NSMutableString *mcopyStr = [str mutableCopy];
NSLog(@"str = %@, copyStr = %@, mcopyStr = %@",str,copyStr,mcopyStr);
NSLog(@"str = %p, copyStr = %p, mcopyStr = %p",str,copyStr,mcopyStr);


log:
str = 0x0, str = 0x7ffee6496a88
str = demo, copyStr = demo, mcopyStr = demo
str = 0x109768080, copyStr = 0x109768080, mcopyStr = 0x600002ca52c0

结论:
1、copy和mutableCopy拷贝出来的对象中的内容和以前内容一致
2、不可变的字符串通过copy操作,没有生成新的对象,而是指向同一内存
3、不可变的字符串通过mutableCopy操作,生成新的可变对象,所以需要生成一个新对象
NSMutableString *str = [NSMutableString stringWithFormat:@"demo"];
NSMutableString *copyStr =  [str copy];
NSMutableString *mcopyStr =  [str mutableCopy];
    
NSLog(@"str = %@, copyStr = %@, mcopyStr = %@",str,copyStr,mcopyStr);
NSLog(@"str = %p, copyStr = %p, mcopyStr = %p",str,copyStr,mcopyStr);

log:
str = demo, copyStr = demo, mcopyStr = demo
str = 0x60000397a370, copyStr = 0xc464b5846da8a473, mcopyStr = 0x60000397a880
结论:
1、copy和mutableCopy拷贝出来的对象中的内容和以前内容一致
2、可变的字符串通过copy操作,生成新的对象
3、可变的字符串通过mutableCopy操作,生成新的可变对象

copy的用途

@interface Person : NSObject
@property (nonatomic,strong) NSString *firstName;
@property (nonatomic,copy) NSString *lastName;
@end

NSMutableString *firstNameStr = [[NSMutableString alloc]initWithFormat:@"firstName-AA"];
Person *p = [[Person alloc]init];
p.firstName = firstNameStr;
NSLog(@"%@",p.firstName);
[firstNameStr appendString:@"aa"];
NSLog(@"%@",p.firstName);
NSMutableString *lastNameStr = [[NSMutableString alloc]initWithFormat:@"lastNameStr-BB"];
p.lastName = lastNameStr;
NSLog(@"%@",p.lastName);
[lastNameStr appendString:@"bb"];
NSLog(@"%@",p.lastName);

log:
firstName-AA
firstName-AAaa
lastNameStr-BB
lastNameStr-BB

自定义类的实现copy(NSCopying协议)

- (id)copyWithZone:(nullable NSZone *)zone;
- (id)mutableCopyWithZone:(nullable NSZone *)zone;

看个例子

#import <Foundation/Foundation.h>
@interface Phone : NSObject<NSCopying>
@property (nonatomic,copy,readonly) NSString *name;
@property (nonatomic,assign,readonly) NSInteger price;

- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price;
@end


#import "Phone.h"
@implementation Phone
- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price{
    self = [super init];
    if (self) {
        _name = [name copy];
        _price = price;
    }
    return self;
}
- (id)copyWithZone:(NSZone *)zone{
    Phone *phone = [[[self class] allocWithZone:zone] initWithName:_name withPrice:_price];
    return phone;
}

Phone *p = [[Phone alloc]initWithName:@"iPhone" withPrice:999];
NSLog(@"%p--%@--%zd",p,p.name,p.price);
Phone *p1 = [p copy];
NSLog(@"%p--%@--%zd",p1,p1.name,p1.price);

log:
0x60000002cce0--iPhone--999
0x6000000371c0--iPhone--999

注:在- (id)copyWithZone:(NSZone *)zone方法中,一定要通过[self class]方法返回的对象调用allocWithZone:方法。因为指针可能实际指向的是PersonModel的子类。这种情况下,通过调用[self class],就可以返回正确的类的类型对象。

上一篇 下一篇

猜你喜欢

热点阅读