[Objective-c 基础

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 @end
14 
15 @implementation Student
16 
17 - (void) setAge:(int) newAge
18 {
19     if (newAge <= 0)
20     {
21         age = 1;
22     }
23     else
24     {
25         age = newAge;
26     }
27 }
28 
29 - (int) age
30 {
31     return age;
32 }
33 
34 - (void) study
35 {
36     NSLog(@"%d岁的学生在学习", age);
37 }
38 
39 @end
40 
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
原文地址:https://www.cnblogs.com/hellovoidworld/p/4119339.html