本文介绍: 类扩展——一种特别的类别

0 引言

如何为现有类添加新的方法

  1. 通过继承实现创建子类,在子类中添加实现功能)——一般不会去继承类簇
  2. 通过类别实现(利用objective-c动态运行时分配机制,为现有类添加方法)。

1 定义

  • 扩展:一种特殊的类别

2 特点

3 示例代码

主要包括三部分代码main.m、Thing.h、Thing.m
其中:。

//
//  Things.h
//  12.04 ClassExtension
//
//  Created by Waqar Malik on 3/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Things : NSObject
@property (assign) NSInteger thing1;
@property (readonly, assign) NSInteger thing2;

- (void)resetAllValues;
@end
/*@interface Things ()   //类扩展特点1+特点2;
{
    NSInteger thing4;   //类扩展特点3:添加一个名为thing4的实例变量,该实例变量具有私有属性,即:即使类扩展定义在.h文件中,things4仍然无法在main文件中被访问。
}
@property (readwrite, assign) NSInteger thing2;   //类扩展特点4:在类扩展(类别)中修改属性,仅在本文件中起作用;如:main函数中thing2属性仍为只读属性。
@property (assign) NSInteger thing3;       //在类扩展(类别)中修添加的实例变量,也仅在本文件中起作用;如:main函数中thing3不可见。
@end*/

 //
//  Things.m
//  12.04 ClassExtension
//
//  Created by Waqar Malik on 3/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "Things.h"

//将类扩展写在.m文件,而非.h文件,对外不提供,私有化。
@interface Things ()
{
    NSInteger thing4;   //类扩展作用1:添加一个名为thing4的实例变量
}
@property (readwrite, assign) NSInteger thing2;      //在类扩展(类别)中修改的属性,仅在本文件中起作用;如:main函数中thing2属性仍为只读属性。
@property (assign) NSInteger thing3;       //在类扩展(类别)中修添加的实例变量,也仅在本文件中起作用;如:main函数中thing3不可见。
@end

@implementation Things
//对thing
@synthesize thing1;
@synthesize thing2;
@synthesize thing3;

- (void)resetAllValues
{
    self.thing1 = 200;
    self.thing2 = 300;
    self.thing3 = 400;
    thing4 = 5;
}

- (NSString *) description
{
    NSString *desc = [NSString stringWithFormat: @"%d %d %d %d",
                      thing1, thing2, thing3,thing4];
    
    return (desc);
    
} // description
@end

//
//  main.m
//  ClassExtension
//
//  Created by Waqar Malik on 3/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Things.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        Things *things = [[Things alloc] init];
        things.thing1 = 1;
        // things.thing2 = 2;                 //Assignment to readonly property
        //things.thing3 = 2;               //Property 'thing3' not found on object of type 'Things *'
        //things.thing4=3;          //Property 'thing4' not found on object of type 'Things *'; 私有化了
        NSLog(@"%@", things);
        [things resetAllValues];
        NSLog(@"%@", things);
    }
    return 0;
}

原文地址:https://blog.csdn.net/yinhaijing_ss/article/details/126041674

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_5991.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注