简体   繁体   English

[矩形类]中使用的类方法

[英]Class method used in [Rectangle class]

What is the method "class" for, as used in [Rectangle class]? 在[矩形类]中使用的“类”方法是什么? Does it create an instance of Rectangle? 是否创建Rectangle的实例? I thought that was 我以为那是

Rectangle *aRectangle = [[Rectangle alloc] init]. 

Why/When would I ever use [Rectangle class]? 为什么/何时使用[矩形类]?

Here are probably the two most common uses for [Rectangle class] : 这可能是[Rectangle class]的两个最常见的用法:

  1. You can use [Rectangle class] to check whether an object is an instance of Rectangle (or an instance of a subclass of Rectangle ): 可以使用[Rectangle class]来检查对象是否是的一个实例Rectangle (或子类的实例Rectangle ):

     if ([object isKindOfClass:[Rectangle class]]) { Rectangle *rect = (Rectangle *)object; // ... use rect } 

    But if you just have one message to send, it might be better to just check whether the object understands the message you want to send it: 但是,如果您只发送一条消息,最好检查对象是否理解您要发送的消息:

     if ([object respondsToSelector:@selector(area)]) { double area = [object area]; // etc. } 
  2. You can use the class object to create an instance of the class: 您可以使用class对象创建该类的实例:

     Class rectangleClass = [Rectangle class]; Rectangle *rectangle = [[rectangleClass alloc] init]; 

    Why would you want to do that? 你为什么想这么做? Well, if you know the class explicitly at the location (in your code) where you want to create it, you wouldn't. 好吧,如果您在要创建类的位置(在代码中)显式知道了该类,则不会。 You'd just say [[Rectangle alloc] init] , for example. 例如,您只需要说[[Rectangle alloc] init]

    But consider UIView . 但是考虑一下UIView Every UIView creates and manages a CALayer . 每个UIView都会创建和管理一个CALayer By default, it creates an instance of CALayer , but you might want your view to use a CAShapeLayer (example) or a CAGradientLayer (example) instead. 默认情况下,它创建CALayer的实例,但是您可能希望视图使用CAShapeLayer (示例)CAGradientLayer (示例)代替。 You need a way to tell UIView to create an instance of a different class. 您需要一种方法来告诉UIView创建其他类的实例。

    You can tell your UIView subclass what kind of layer to create by overriding the layerClass class method : 您可以通过覆盖layerClass类方法来告诉您的UIView子类要创建哪种层:

     @implementation MyShapeView + (Class)layerClass { return [CAShapeLayer class]; } 

    When it's time for a MyShapeView to create its layer, it'll send itself layerClass and create an instance of whatever class it gets back. 当需要使用MyShapeView创建其图层时,它将发送自身layerClass并创建它返回的任何类的实例。 The code probably looks something like this: 该代码可能看起来像这样:

     @implementation UIView { CALayer *_layer; } - (CALayer *)layer { if (_layer == nil) { _layer = [[[self layerClass] alloc] init]; _layer.delegate = self; } return _layer; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM