1.NSString,NSMutableString,NSArray,NSMutableArray,NSDictionary,NSMutableDictionary的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
网友评论