Reputation: 137
I have an object with a 2d C array (can't figure out how to do the same with NSArray) and I also need this object to provide deep copies of itself. I'm trying to implement the NSCopying protocol except when trying to make a copy of the c array i can't figure out how to reference self's array and the copy's array. Since it's not a property and obj c doesn't support c array properties as far as i know, i don't know how to set the new copy's array.
I've tried typedefing my array as a struct but I'm also using ARC so that isn't a valid solution
Hopefully I'm not missing something basic. Thanks.
Upvotes: 0
Views: 205
Reputation: 34829
You can use the ->
notation to access the instance variables of the copied object. When making a deep copy, each object in the array must be copied.
// 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;
}
Upvotes: 2