//延展Extension,是为类扩充私有的方法,以及私有的实例变量,和分类Category相比,延展定义的方法是私有的,而且还可以定义实例变量(私有的)。
//@interface 开头 + 类名(哪一个类的延展) + 小括号,小括号内填写的是延展名,一般情况下都省略。 @end结束 (写在.m文件里)
main函数中的完整代码为:
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person *person = [[Person alloc] initWithName:@"ruby" sex:@"man" age:23]; [person setName:@"Ruby"]; person.age = 13; // [person sayHi]; } return 0; }
创建一个Person类
Person.h中的完整代码为:
#import <Foundation/Foundation.h> @interface Person : NSObject { NSString *_name; //姓名 NSString *_sex; //性别 NSInteger _age; //年龄 } #pragma mark - setter and getter @property (nonatomic, retain) NSString *name; @property (nonatomic ,retain) NSString *sex; @property (nonatomic) NSInteger age; #pragma mark - init method - (id)initWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age; @end
Person.m中的完整代码为:
#import "Person.h" @interface Person () { NSMutableArray *_personArr; } - (void)sayHi; @end @implementation Person #pragma mark - init method - (id)initWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age { self = [super init]; if (self) { self.name = name; self.sex = sex; self.age = age; [self sayHi]; } return self; } #pragma mark - sayHi - (void)sayHi { NSLog(@"This is a private method:%@, %@, %ld", self.name, self.sex, self.age); } @end
本文出自 “一毛” 博客,请务必保留此出处http://winann.blog.51cto.com/4424329/1436073
iOS开发OC基础:延展Extension,布布扣,bubuko.com
原文地址:http://winann.blog.51cto.com/4424329/1436073