Objective-C copy, 나만 보면 돼.
약간은 기본 클래스를 통해copyWithZone과mutableCopyWithZone을 실현하여 수동적인 번거로움을 줄이고 대응하는 값이나copy 등의 조작 코드를 다음과 같이 실현한다.
#import "WXObject.h"
#import
@implementation WXObject
- (id)copyWithZone:(NSZone *)zone {
return [self wx_copyWithZone:zone];
}
- (id)mutableCopyWithZone:(NSZone *)zone {
return [self wx_copyWithZone:zone];
}
- (id)wx_copyWithZone:(NSZone *)zone {
id obj = [[self class] allocWithZone:zone];
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = *(ivars + i);
//
const char *type = ivar_getTypeEncoding(ivar);
NSString *var_type = [NSString stringWithUTF8String:type];
var_type = [var_type stringByReplacingOccurrencesOfString:@"\"" withString:@""];
var_type = [var_type stringByReplacingOccurrencesOfString:@"@" withString:@""];
//
const char *varName = ivar_getName(ivar);
NSString *var_keypath = [NSString stringWithUTF8String:varName];
var_keypath = [var_keypath stringByReplacingOccurrencesOfString:@"_" withString:@""];
//NSLog(@"var_type = %@ var_keypath = %@",var_type,var_keypath);
Class ivarClass = NSClassFromString(var_type);
if ([ivarClass isKindOfClass:[NSObject class]]) {
id temp = [self valueForKeyPath:var_keypath];
if ([temp conformsToProtocol:@protocol(NSCopying)]) {
[obj setValue:[temp copy] forKeyPath:var_keypath];
}else if([temp conformsToProtocol:@protocol(NSMutableCopying)]){
[obj setValue:[temp mutableCopy] forKeyPath:var_keypath];
}
}else {
if (var_keypath) {
[obj setValue:[self valueForKeyPath:var_keypath] forKeyPath:var_keypath];
}
}
}
free(ivars);
return obj;
}
@end
#import "NSArray+Extension.h"
@implementation NSArray (Extension)
+ (instancetype)deepCopyFromArray:(NSArray *)array {
NSMutableArray *temp = [NSMutableArray array];
for (id obj in array) {
[temp addObject:[obj copy]];
}
return [NSArray arrayWithArray:temp];
}
@end
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.