美文网首页
copy & mutableCopy

copy & mutableCopy

作者: xxxxxxxxx_ios | 来源:发表于2018-12-27 09:45 被阅读5次

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]));
    }
}
  • 运行结果


    自定义类实现copy

相关文章

网友评论

      本文标题:copy & mutableCopy

      本文链接:https://www.haomeiwen.com/subject/wqwllqtx.html