//延展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
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。