- [MyClassName copyWithZone:]无法识别的选择器发送到实例

时间:2012-07-09 08:55:04

标签: iphone objective-c class crash copy

我的申请因以下原因而崩溃:

  

- [MyClassName copyWithZone:]无法识别的选择器发送到实例

我有两节课。我们说Class1和Class2。

Class1看起来像:

Class1.h

@interface Class1 : NSObject {
    NSString *imagemd5CheckSum;
    UIImage *image;
    NSData *fileChunkData;
}

@property (nonatomic, copy)NSString *imagemd5CheckSum;
@property (nonatomic, copy)UIImage *image;
@property (nonatomic, copy)NSData *fileChunkData;

@end

Class1.m

@implementation Class1

@synthesize image;
@synthesize fileChunkData;
@synthesize imagemd5CheckSum;

-(id) init{
    [self setImage:nil];
    [self setFileChunkData:nil];
    [self setImagemd5CheckSum:@""];

    return self;
}

-(void)dealloc{
    [imagemd5CheckSum release];
    [image release];
    [fileChunkData release];

    fileChunkData = nil;
    imagemd5CheckSum = nil;
    image = nil;

    [super dealloc];
}
@end

**

  

Class2看起来像

**

Class2.h


#import "Class2.h"
@interface Class2 : NSObject {
    Class1 *obj1;
    Class1 *obj2;
    Class1 *obj3;
}

@property (nonatomic, copy)Class1 *obj1;
@property (nonatomic, copy)Class1 *obj2;
@property (nonatomic, copy)Class1 *obj3;

@end

Class2.m


@implementation Class2

@synthesize obj1,obj2,obj3;

-(id) init{
    [self setObj1:nil];
    [self setObj2:nil];
    [self setObj3:nil];

    return self;
}

-(void)dealloc{
    [obj1 release];
    [obj2 release];
    [obj3 release];

    obj1 = nil;
    obj2 = nil;
    obj3 = nil;

    [super dealloc];
}
@end

崩溃情况

Class2 *class2 = [[Class2 alloc] init];

Class1 *class1 = [[Class1 alloc] init];

[class1 setImagemd5CheckSum:@"this is md5"];
[class1 setImage:myimage];
[class1 setFileChunkData:myData];

[class2 setObj1:class1]; // This line is crashed..

...

当我拨打[class2 setObj1:class1];时,应用程序崩溃了原因:

  

- [Class1 copyWithZone:]无法识别的选择器发送到实例

如何解决此问题?

2 个答案:

答案 0 :(得分:71)

您的-setObj1:方法被声明为copy,因此它会在-copy对象上调用Class1-copy只需致电-copyWithZone:nil。因此,您需要实施NSCopying协议(这意味着实施-copyWithZone:),或将您的财产从copy更改为retain

答案 1 :(得分:49)

要让您的班级回复copyWithZone:,您必须在班级中实施NSCopying协议。您必须覆盖copyWithZone:方法。

例如:

首先,您必须在接口声明中实现NSCopying协议。

@interface MyObject : NSObject <NSCopying>

然后覆盖copyWithZone方法,例如,

- (id)copyWithZone:(NSZone *)zone
{
    id copy = [[[self class] alloc] init];

    if (copy)
    {
        // Copy NSObject subclasses
        [copy setVendorID:[[self.vendorID copyWithZone:zone] autorelease]];
        [copy setAvailableCars:[[self.availableCars copyWithZone:zone] autorelease]];

        // Set primitives
        [copy setAtAirport:self.atAirport];
    }

    return copy;
}

如果这有助于你,我很高兴。

Reference