OC-031.类扩展

来源:互联网 发布:浪潮软件免费下载 编辑:程序博客网 时间:2024/06/08 09:58
类扩展:为类增加私有的属性和方法,只能在类内部调用,外部不能使用。(一般情况下直接在.m文件中写,不再另建.h文件)
命名规范 interface 扩展类名 ()

如何增加一个分类操作步骤:右键点击New File->Objective-C.File->第一行输入名称,第二行选择Extension,第三行选择需要扩展的类名。

#import <Foundation/Foundation.h>//------main//类扩展:一般情况下直接在.m文件中写,为类增加私有的属性和方法//命名规范 interface 扩展类名 ()//如何增加一个分类操作步骤:右键点击New File->Objective-C.File->第一行输入名称,第二行选择Extension,第三行选择需要扩展的类名。#import "LSPerson.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        LSPerson *per = [[LSPerson alloc] init];//        [per show];私有方法是不能在外界调用,只能在类的内部调用//        per.age = 10; 因为类扩展里面的setter方法是私有方法,所以不能在外界调用        [per say];    }    return 0;}
#import <Foundation/Foundation.h>//------LSPerson.h@interface LSPerson : NSObject//@property(nonatomic,assign)int age;这里声明的setter和getter是公开的方法-(void) say;@end
#import "LSPerson.h"//------LSPerson.m//#import "LSPerson+show.h"一般不再重新另建文件夹来进行类扩展,而是写到.m文件中,不然还要导入文件//命名规范 interface 类名 ()/* 1、小括号中不可以有任何内容 2、一般写在.m文件中,增加类的私有成员变量、属性、方法 */@interface LSPerson ()@property(nonatomic,assign)int age;//这声明的setter和getter是私有的方法,不能在外界直接赋值-(void) show;//增加私有方法  好处:当方法太多,方便查找私有方法,按command+左键@end@implementation LSPerson-(void) show{    NSLog(@"age = %d",_age);}-(void) say{    self.age = 28;    [self show]; //私有方法只能在类中调用}@end
#import "LSPerson.h"//一般不再另建.h文件去写类扩展,直接在.m文件中写---文件名格式为LSPerson_age.h @interface LSPerson () //命名规范 interface 类名 ()@end






0 0
原创粉丝点击