NSCopying简析
用到NSCopying的时候并不多,但还是有必要知道最基本的用途,比方说数组的拷贝操作,需要注意的是,数组的拷贝操作并不是执行了 copy 方法,而是需要执行 initWithArray:copyItems: ,这点需要注意.
源码:
//
// Model.h
// NSCopy
//
// Created by YouXianMing on 15/5/2.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Model : NSObject <NSCopying/* 继承NSCopying协议 */>
// 对象类型
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;
// 基本数据类型
@property (nonatomic, assign) BOOL isMale;
@end
//
// Model.m
// NSCopy
//
// Created by YouXianMing on 15/5/2.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
//
#import "Model.h"
@implementation Model
- (id)copyWithZone:(NSZone *)zone {
// 获取拷贝内容
Model *copy = [[[self class] allocWithZone:zone] init];
// 基本属性的类型本身实现了copy协议
copy.name = [_name copy];
copy.age = [_age copy];
// 常规类型属性仅仅需要赋值即可
copy.isMale = _isMale;
return copy;
}
@end
控制器源码:
//
// ViewController.m
// NSCopy
//
// Created by YouXianMing on 15/5/2.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
//
#import "ViewController.h"
#import "Model.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 对象1
Model *modelOne = [Model new];
modelOne.name = @"YouXianMing";
modelOne.age = @(28);
// 对象1的复制
Model *modelCopy = [modelOne copy];
// 打印信息
NSLog(@"%@ %@", modelOne, modelOne.name);
NSLog(@"%@ %@", modelCopy, modelCopy.name);
// 数组
NSArray *array = @[modelOne, modelCopy];
// 数组的复制
NSArray *arrayCopy = [[NSArray alloc] initWithArray:array copyItems:YES];
// 打印信息
NSLog(@"%@", array);
NSLog(@"%@", arrayCopy);
}
@end
简单的分析:
时间: 2024-12-01 14:33:48