我有两个数组。首先包含自定义对象。现在我想将第一个数组的所有对象复制到另一个数组中。为此,我使用以下代码。
数组。
arr_post=[[NSMutableArray alloc]init];
copy_arr_user_post=[[NSMutableArray alloc]init];
我正在像这样将对象添加到其中。
for(i=0;i<[arr_main count];i++)
{
Post *obj=[[Post alloc]init];
obj.name=@"abc";
obj.category=@"social";
[arr_post addObjectbj];
}
现在我像这样复制到另一个数组
[arr_post addObject:user_post];
Post *objectCopy = [user_post copy]; //create a copy of our object
[copy_arr_user_post addObject: objectCopy]; //insert copy into other array
在 Post.h 中
@interface Post : NSObject<NSCopying>
在 Post.m 中
- (id)copyWithZoneNSZone *)zone
{
// Copying code here.
Post *another =[[[self class] allocWithZone:zone] init];
another.id=self.id;
another.category=self.category;
return another;
}
但它不会复制我得到空值的对象。为什么?
Best Answer-推荐答案 strong>
我发现一种比 NSCopyng 更快的方法
-用这两种方法创建一个NSObject类
#import <objc/runtime.h>
-(id)deepCopy
{
NSArray *tmpArray = @[self];
NSData *buffer = [NSKeyedArchiver archivedDataWithRootObject:tmpArray];
return [NSKeyedUnarchiver unarchiveObjectWithData:buffer][0];
}
- (NSMutableArray *)allProperties
{
NSMutableArray *props = [NSMutableArray array];
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
//Excluding all readOnly properties
unsigned int numOfAttributes;
objc_property_attribute_t *propertyAttributes = property_copyAttributeList(property, &numOfAttributes);
BOOL foundReadonly = NO;
for ( unsigned int ai = 0; ai < numOfAttributes; ai++ )
{
switch (propertyAttributes[ai].name[0]) {
case 'T': // type
break;
case 'R': // readonly
foundReadonly = YES;
break;
case 'C': // copy
break;
case '&': // retain
break;
case 'N': // nonatomic
break;
case 'G': // custom getter
break;
case 'S': // custom setter
break;
case 'D': // dynamic
break;
default:
break;
}
}
free(propertyAttributes);
if (!foundReadonly)
{
NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSASCIIStringEncoding];
[props addObject:propertyName];
}
}
free(properties);
return props;
}
-让你的对象符合 NSCoding
#pragma mark - NSCoding
- (instancetype)initWithCoderNSCoder *)decoder {
self = [super init];
if (self)
{
NSArray *keys = [self allProperties];
for (NSString *key in keys)
{
[self setValue:[decoder decodeObjectForKey:key] forKey:key] ;
}
}
return self;
}
- (void)encodeWithCoderNSCoder *)aCoder
{
NSArray *keys = [self allProperties];
for (NSString *key in keys)
{
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
}
-导入类别
现在您可以复制任何类型的对象
MYObject *copy = [originalObject deepCopy];
NSArray *arrayWithCopiedObjects = [originalArray deepCopy];
等等……
关于ios - 如何在 Objective-C 中复制自定义对象?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/33295204/
|