【问题标题】:Question about setting the key of NSDictionary关于设置NSDictionary的key的问题
【发布时间】:2011-08-08 03:33:15
【问题描述】:

我有一个名为 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 的对象设置为 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;
}

谢谢!

【问题讨论】:

    标签: iphone objective-c ipad


    【解决方案1】:

    你也必须在 copyWithZone 中复制 str 和 num:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2015-01-23
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2017-06-23
      相关资源
      最近更新 更多