//延展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