copy & mutableCopy

2018-12-27  本文已影响5人  xxxxxxxxx_ios

1.NSString,NSMutableString,NSArray,NSMutableArray,NSDictionary,NSMutableDictionary的copy与mutableCopy操作。

copy & mutableCopy

2.自定义类如何实现copy功能(遵守NSCopying协议)

.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface YMPerson : NSObject <NSCopying>
/** age */
@property (nonatomic, assign) int age;
@end

NS_ASSUME_NONNULL_END

.m

#import "YMPerson.h"

@implementation YMPerson

- (id)copyWithZone:(NSZone *)zone {
    
    YMPerson *person = [YMPerson allocWithZone:zone];
    person.weight = self.weight;
    return person;
}

@end

使用

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "YMPerson.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {
        
        YMPerson *p = [[YMPerson alloc] init];
        p.age = 20;
        p.weight = 50;
        
        YMPerson *p1 = [p copy];
        p1.age = 30;
        p1.weight = 60;
        
        NSLog(@" p == %p, p1 == %p",p,p1);
        NSLog(@" p.age == %d p1.age == %d",p.age,p1.age);
        
        
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}
上一篇 下一篇

猜你喜欢

热点阅读