美文网首页
Objective-C 类的定义、扩展(Extension)、分

Objective-C 类的定义、扩展(Extension)、分

作者: 张科_Zack | 来源:发表于2021-08-27 16:05 被阅读0次

    Objective-C 类定义

    Objective-C 类定义使用 @interface@implementation 来完成。其中 @interface 用于申明 public接口为了在其它类中向目标类类的对象发消息── 即 @interface 申明的是类的 消息列表@implementation 则是 public 接口中申明的方法实现部分── 即其它类向目标类对象发送消息后,目标类对象做出响应的地方。一个 Person 类被定义如下:

    @interface Person: NSObject
    @property(nonatomic, copy)NSString *name;
    - (void)sayHelloToWorld:(NSString *)string;
    
    @end
    
    
    @implementation Person
    
    - (void)sayHelloToWorld:(NSString *)string {
        NSLog(@"%@ say hello to world!", self.name);
    }
    
    @end
    

    Objective-C 类扩展(Extension)

    Objective-C 中类的扩展是为类的实现部分@implementation提供对私有方法以及变量的接口, 其格式为如下, 只是在如申明接口的时候在类名后加一对小括号()。

    @interface ClassName()
    
    @end
    

    Extension 一个非常好用的地方则是对一个在类 public 接口部分申明一个只读属性(readonly),在类实现的地方可以读写这个属性,可以通过在 @implementation 通过扩展修改 readonly 属性为 readwrite, 例子如下

    @interface Person: NSObject
    @property(nonatomic, copy)NSString *name;
    @property(nonatomic, readonly) NSString *des;
    
    - (void)sayHelloToWorld:(NSString *)string;
    
    @end
    
    @interface Person()
    @property(nonatomic,  readwrite)NSString *des;
    
    @end
    
    
    @implementation Person
    
    - (void)sayHelloToWorld:(NSString *)string {
        NSLog(@"%@ say hello to world!", self.name);
        self.des = [NSString stringWithFormat:@"%@ is a good person. Because %@ smile to every one in small town.", self.name, self.name ];
    }
    
    @end
    

    当然也可以通过直接在视线中调用私有变量 _des 来达到同样目的,此外 readonly 和 readwrite 的区别是 readonly 不会合成 set 方法而 readwrite 则会。

    Objective-C 类的分类(Category)

    类的分类(Category)格式则是在@interface 、@implementation 类名后加上一对小括号并在小括号中加上分类名称,例子如下, 对Person 加一个 Professional 分类。

    @interface Person (Professional)
    - (void)focus;
    - (void)experience;
    @end
    
    @implementation Person (Professional)
    
    - (void)focus {
        NSLog(@"A professional always focus to work.");
    }
    - (void)experience {
        NSLog(@"A professional always must have a lot of experience.");
    
    }
    
    @end
    

    值得注意的是分类(Category)是不可以添加属性的,如果想加则可以通过运行时方式。

    相关文章

      网友评论

          本文标题:Objective-C 类的定义、扩展(Extension)、分

          本文链接:https://www.haomeiwen.com/subject/fdpmiltx.html