56

我的应用程序崩溃的原因是:

-[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 看起来像

**

类2.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:] 无法识别的选择器发送到实例

我该如何解决这个问题?

4

2 回答 2

76

您的-setObj1:方法被声明为copy,因此它调用-copy您的Class1对象。-copy只是打电话-copyWithZone:nil。因此,您要么需要实现NSCopying协议(这意味着实现-copyWithZone:),要么将您的属性从 更改copyretain

于 2012-07-09T09:01:49.760 回答
53

为了让您的班级响应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;
}

如果这对您有帮助,我很高兴。

参考

于 2012-07-09T09:06:21.587 回答