ios - 如何在 Objective-C 中复制自定义对象?
<p><p>我有两个数组。首先包含自定义对象。现在我想将第一个数组的所有对象复制到另一个数组中。为此,我使用以下代码。</p>
<p><strong>数组。</strong></p>
<pre><code>arr_post=[init];
copy_arr_user_post=[init];
</code></pre>
<p>我正在像这样将对象添加到其中。</p>
<pre><code>for(i=0;i<;i++)
{
Post *obj=[init];
obj.name=@"abc";
obj.category=@"social";
;
}
</code></pre>
<p>现在我像这样复制到另一个数组</p>
<pre><code> ;
Post *objectCopy = ; //create a copy of our object
; //insert copy into other array
</code></pre>
<p><strong>在 Post.h 中</strong></p>
<pre><code>@interface Post : NSObject<NSCopying>
</code></pre>
<p><strong>在 Post.m 中</strong></p>
<pre><code>- (id)copyWithZone:(NSZone *)zone
{
// Copying code here.
Post *another =[[ allocWithZone:zone] init];
another.id=self.id;
another.category=self.category;
return another;
}
</code></pre>
<p>但它不会复制我得到空值的对象。为什么?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我发现一种比 NSCopyng 更快的方法</p>
<p>-用这两种方法创建一个NSObject类</p>
<pre><code>#import <objc/runtime.h>
-(id)deepCopy
{
NSArray *tmpArray = @;
NSData *buffer = ;
return ;
}
- (NSMutableArray *)allProperties
{
NSMutableArray *props = ;
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties;
//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.name) {
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 = [ initWithCString:property_getName(property) encoding:NSASCIIStringEncoding];
;
}
}
free(properties);
return props;
}
</code></pre>
<p>-让你的对象符合 NSCoding</p>
<pre><code>#pragma mark - NSCoding
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = ;
if (self)
{
NSArray *keys = ;
for (NSString *key in keys)
{
forKey:key] ;
}
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
NSArray *keys = ;
for (NSString *key in keys)
{
forKey:key];
}
}
</code></pre>
<p>-导入类别</p>
<p>现在您可以复制任何类型的对象</p>
<pre><code>MYObject *copy = ;
NSArray *arrayWithCopiedObjects = ;
</code></pre>
<p>等等……</p></p>
<p style="font-size: 20px;">关于ios - 如何在 Objective-C 中复制自定义对象?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/33295204/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/33295204/
</a>
</p>
页:
[1]