4

Cocoahead 能否解释一下为什么 UIView 及其子类不采用 NSCopying 协议?

我可以从哲学上理解为什么 UITouch 不符合复制要求,因为它是一个非常临时的对象。通过 UIView,它的子类,尤其是 UIButton,似乎应该能够被复制。

当然,Apple 有充分的理由以他们的方式做事。你知道他们的原因吗?

4

3 回答 3

4

有趣的问题。除了查克的回答,我想补充一点,原因可能是苹果做出了这个设计决定……就这么简单;没有真正的具体原因,但这是做出的决定。

我还可以假设这个决定可能已经做出,因为UIView它被用作其他几个类的子类,并且工程师不想强行强加于NSCopying子类。

于 2009-10-12T19:27:17.110 回答
4

他们问的问题似乎不是“为什么不呢?” 但是“为什么要这样做?” 这样做没有什么意义。很少需要复制实时视图。通常,模板视图是通过 NSCoding 协议(即使用 Interface Builder)创建的,这就是可复制视图的所有优点。

于 2009-10-11T23:57:01.537 回答
3

因为NSCopying在对象图的深度(递归)副本方面不是很好。例如,[NSArray copy]复制对象列表,而不是对象本身。对象图更好地服务于NSCoding. 巧合的是,支持UIView

如果要复制带有属性的自定义视图,则必须支持NSCoding. 例如,

@interface SKCustomCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel* nameLabel;
@property (strong, nonatomic) IBOutlet UIView* topView;

@end


static NSString* propertiesKey = @"SKCustomCellProperties";

@implementation SKCustomCell

@synthesize nameLabel;
@synthesize topView;

- (id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder: aDecoder];
    [self setValuesForKeysWithDictionary: [aDecoder decodeObjectForKey: propertiesKey]];
    return self;
}

- (void) encodeWithCoder:(NSCoder *)aCoder
{
    [super encodeWithCoder: aCoder];

    [aCoder encodeObject: [self dictionaryWithValuesForKeys: [[NSArray alloc] initWithObjects: @"nameLabel", @"topView", nil] forKey: propertiesKey];
}


@end
于 2012-05-15T13:10:56.403 回答