首页 > 代码库 > [Objective-c 基础 - 2.1] 封装

[Objective-c 基础 - 2.1] 封装

A.封装内部细节,根据需求暴露方法

 1 #import <Foundation/Foundation.h> 2  3 @interface Student : NSObject 4 { 5     int age; 6 } 7  8 - (void) setAge:(int) newAge; 9 - (int) age;10 11 - (void) study;12 13 @end14 15 @implementation Student16 17 - (void) setAge:(int) newAge18 {19     if (newAge <= 0)20     {21         age = 1;22     }23     else24     {25         age = newAge;26     }27 }28 29 - (int) age30 {31     return age;32 }33 34 - (void) study35 {36     NSLog(@"%d岁的学生在学习", age);37 }38 39 @end40 41 42 int main()43 {44     Student *stu = [Student new];45     [stu setAge:21];46     [stu study];47    48     NSLog(@"这个学生的年龄是%d", [stu age]);49    50     return 0;51 }
 
B.封装规范
使用下划线开头命名成员变量
 1 @interface Student : NSObject 2 { 3     int _no; 4     Sex _sex; 5 } 6  7 - (Sex) sex; 8 - (void) setSex:(Sex) newSex; 9 - (int) no;10 - (void) setNo:(int) no;11 12 @end

 

 

[Objective-c 基础 - 2.1] 封装