不像C++有关键词private来申明私用方法(实例变量除外),OC没有关键词来申明是私有方法,当我们可以用类的extension来实现私有方法
1、Person.m实现在文件中@interface…@end来申明私有方法(头文件中未申明),那这个方法不能在其他对象中调用
#import "Person.h" @interface Person() //括号里没有写东西,如果写了就是类别,不写就是extension - (void) whereLive; @end @implementation Person @synthesize name; @synthesize age; - (void) whereLive{ NSLog(@"living in xiaoshan"); } - (NSString *) description{ NSString *desc; desc = [[NSString alloc] initWithFormat:@"Person:name is %@,age is %ld", self.name,(long)self.age ]; return desc; } @end |
2、到main函数中来调用
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person *person = [[Person alloc] init]; person.name = @"liyi(my son)"; person.age = 1; NSLog(@"%@",person); [person whereLive]; } return 0; } |
Xcode会报whereLive方法未定义,找不到
其实我们可以间接方式来进行私有方法,修改代码
Person.h:
#import <Foundation/Foundation.h> @interface Person : NSObject { NSString *name; NSInteger age; } @property (copy) NSString* name; @property NSInteger age; //定义可以访问私有方法的方法accessPrivate - (void) accessPrivate; @end |
Person.m 定义extension whereLive
#import "Person.h" @interface Person() //括号里没有写东西,如果写了就是类别,不写就是extension - (void) whereLive; @end @implementation Person @synthesize name; @synthesize age; - (void) whereLive{ NSLog(@"living in xiaoshan"); } - (void) accessPrivate{ [self whereLive]; } - (NSString *) description{ NSString *desc; desc = [[NSString alloc] initWithFormat:@"Person:name is %@,age is %ld", self.name,(long)self.age ]; return desc; } @end |
main函数
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person *person = [[Person alloc] init]; person.name = @"liyi(my son)"; person.age = 1; NSLog(@"%@",person); //不直接访问whereLive [person accessPrivate]; } return 0; } |
结果:
2014-04-27 16:43:49.610 Person[10054:303] Person:name is liyi(my son),age is 1 2014-04-27 16:43:49.612 Person[10054:303] living in xiaoshan |
下节介绍内存管理,enjoy it!