关于设置NSDictionary密钥的问题

时间:2011-08-08 03:33:15

标签: iphone objective-c ipad

我有一个名为A的课程;

在A.h

@interface A : NSObject {

    NSString *str;
    NSNumber *num;

}

@property (nonatomic,retain) NSString *str;
@property (nonatomic,retain) NSNumber *num;

A是B的超类。

在B.h

@interface B : A {

    NSString *BStr;

}

@property (nonatomic, retain) NSString *BStr;

@end

现在我需要将B的set对象作为NSDictionary的键。

- (void)viewDidLoad {
    [super viewDidLoad];
    B *key = [[B alloc] init];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:@"object" forKey:key];
}

然后B类应该实施NSCopying协议。

我想知道这段代码是否正确?我应该对A类财产做些什么吗?

在B.m

- (id) copyWithZone:(NSZone *)zone {
    B *copy = [[[self class] allocWithZone:zone] init];
    copy.BStr = [[self.BStr copyWithZone:zone] autorelease];
    return copy;
}

谢谢!

1 个答案:

答案 0 :(得分:0)

您还必须在copyWithZone中复制str和num:

copy.str = [[self.str copyWithZone:zone] autorelease];
copy.num = [[self.num copyWithZone:zone] autorelease];