带有C数组的对象的深层副本

时间:2014-03-25 03:16:23

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

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

我已尝试将我的数组作为结构键入,但我也使用ARC,因此这不是一个有效的解决方案

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

1 个答案:

答案 0 :(得分:2)

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

// 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;
}
相关问题