【问题标题】:Deep copy of object with C array带有 C 数组的对象的深拷贝
【发布时间】:2014-03-25 03:16:23
【问题描述】:

我有一个带有 2d C 数组的对象(不知道如何对 NSArray 做同样的事情),我还需要这个对象来提供其自身的深层副本。我正在尝试实现 NSCopying 协议,除非在尝试复制 c 数组时,我无法弄清楚如何引用 self 的数组和副本的数组。由于它不是一个属性并且据我所知 obj c 不支持 c 数组属性,所以我不知道如何设置新副本的数组。

我尝试将数组定义为结构,但我也在使用 ARC,所以这不是一个有效的解决方案

希望我没有遗漏一些基本的东西。谢谢。

【问题讨论】:

  • 发布您拥有的内容,以便人们可以帮助您编写代码。
  • 既然你提到了 2D NSArray 任务,"How to create a 2D NSArray or NSMutableArray in Objective C"
  • 嗨 WhozCraig。我的外部数组可以包含许多内部数组,所以我宁愿使用更优雅的解决方案,而不是必须在循环中初始化每个数组。但如果我不能,我可能会解决这个问题。

标签: ios objective-c c arrays deep-copy


【解决方案1】:

您可以使用-> 符号来访问复制对象的实例变量。进行深度复制时,必须复制数组中的每个对象。

// define a custom class to store in the array
@interface OtherClass : NSObject <NSCopying>
@property (nonatomic, strong) NSString *string;
@end

@implementation OtherClass
- (id)copyWithZone:(NSZone *)zone
{
    OtherClass *temp = [OtherClass new];
    temp.string = [self.string stringByAppendingString:@" (copy)"];
    return( temp );
}

- (void)dealloc
{
    NSLog( @"OtherClass dealloc: %@", self.string );
}
@end

// define the class that contains a C array of custom objects
@interface SomeClass : NSObject <NSCopying>
{
    OtherClass *array[5][5];
}
@end

@implementation SomeClass
- (id)copyWithZone:(NSZone *)zone
{
    SomeClass *temp = [SomeClass new];

    for ( int i = 0; i < 5; i++ )
        for ( int j = 0; j < 5; j++ )
            temp->array[i][j] = [array[i][j] copy];

    return( temp );
}

- (void)storeObject:(OtherClass *)object atRow:(int)row Col:(int)col
{
    array[row][col] = object;
    object.string = [NSString stringWithFormat:@"row:%d col:%d", row, col];
}

- (void)dealloc
{
    NSLog( @"SomeClass dealloc" );
}
@end

// test code to create, copy, and destroy the objects
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    SomeClass *a = [SomeClass new];

    for ( int i = 0; i < 5; i++ )
        for ( int j = 0; j < 5; j++ )
            [a storeObject:[OtherClass new] atRow:i Col:j];

    SomeClass *b = [a copy];

    NSLog( @"Releasing A" );
    a = nil;

    NSLog( @"Releasing B" );
    b = nil;
}

【讨论】:

  • 看起来不错,只是想问一下我应该注意哪些额外的内存管理问题?
  • 我不这么认为。 AFAIK,当对象本身被释放时,实例变量被释放。当然,如果你把malloc的物品放入数组中,那么你必须将dealloc方法重写为free那些物品。
  • @K.He 我想我应该问,“你在数组中存储了什么?”
  • 我正在存储 NSObject 的自定义子类。 memcpy 是否也从原始数组中分配单独的内存?
  • 好的,我以为你在存储原语。我将更新示例代码。
猜你喜欢
  • 2011-04-26
  • 2012-06-19
  • 1970-01-01
  • 2015-11-28
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 2017-08-30
相关资源
最近更新 更多