Why doesn't UIView (or it's subclasses) adopt the NSCopying Protocol?

隐身守侯 提交于 2020-01-02 07:35:09

问题


Can a Cocoahead please explain why UIView and it's sub classes don't adopt the NSCopying Protocol?

I can see, philosophically, why UITouch would not be copy compliant, as it's a very temporal object. By UIView, and it's subclasses, especially UIButton, seem like they should be able to be copied.

Certainly Apple has good reasons for doing things the way they do. Do you know their reason?


回答1:


It would seem the question they asked wasn't "Why not?" but "Why do it?" There's little point to doing so. There's rarely a need to copy a live view. Usually, template views are created through the NSCoding protocol (i.e. with Interface Builder), and that's about all a copyable view would be good for.




回答2:


Interesting question. In addition to Chuck's answer I wanted to add that the reason is possibly because Apple made that design decision... Just that simple; no real specific reason but that was the decision made.

I can also postulate that this decision might have been made because UIView is used as a subclass for a few other classes and the engineers didn't want to impose NSCopying forcefully on the subclasses.




回答3:


Because NSCopying is not so great at deep (recursive) copies of object graphs. For instance, [NSArray copy] copies the list of objects, not the objects themselves. Object graphs are better served by NSCoding. Which in a happy coincidence is supported by UIView.

If you want to copy custom view with properties, you'll have to support NSCoding. E.g.,

@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


来源:https://stackoverflow.com/questions/1552118/why-doesnt-uiview-or-its-subclasses-adopt-the-nscopying-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!