oc学习笔记-set和get函数 基础(Foundation)面向对象之封装方法

 1 #import <Foundation/Foundation.h>
 2 /************************************
 3  *oc get(readonly只读) set(只写)函数 练习   
 4  *set方法 提供一个方法给外界设置成员变量值  可以在方法里面对参数就行过滤
 5  *命名规范:1>方法名必须以set开头 2>set后面跟上成员变量名称 其名称首字母必然大写3>返回值一定是void  4>一定要接受一个参数
 6  *get 方法作用返回对象内部成员变量 参数类型跟成员变量类型一致 5>形参的名称不能跟成员变量名一致。
 7  命名规范:返回值类型与成员变量类型一致  方法名跟成员变量量一致  不需要接受任何参数
 8  *cc 07-set方法.m  -framework Foundation 
 9  ************************************/
10 @interface students : NSObject
11 {
12     int age;
13 }
14 - (void)setAge : (int)newAge;
15 - (int)age;
16 - (void)print;
17 @end
18 @implementation students
19 //set方法
20 - (void)setAge : (int)newAge
21 {
22     if(newAge<=1)
23     {
24         age = 1;
25     }
26 }
27 //get 方法
28 - (int)age
29 {
30     return age;
31 }
32 - (void)print
33 {
34     NSLog(@"%d",age);
35 }
36 @end
37 
38 int main()
39 {
40    students *stu  = [ students new ];
41     [stu setAge : -10];
42     [stu print];
43     NSLog(@"学生年龄是%d",[stu age]);
44     return 0;
45 }

 封装 

 1 #import <Foundation/Foundation.h>
 2 /*
 3  *oc封装 好处:1>过滤不合理的值 2>屏蔽内部赋值过程3>让外界不必关注内部细节
 4  *外部访问内部成员变量(_标记)练习
 5  */
 6 typedef  enum
 7 {
 8     sexMan,
 9     sexWomen
10 } Sex;
11 
12 @interface results : NSObject
13 {
14     int _cScore;//c语言得分
15     int _ocScore;//oc得分
16     Sex _sex;//性别
17 }
18 - (void)setCscore : (int)cScore;
19 - (int)cScore;
20 
21 - (void)setOCscore : (int)OcScore;
22 - (int)OcScore;
23 
24 - (void)setSex : (Sex)sex;
25 - (Sex)sex;
26 
27 - (int)total;
28 - (int)average;
29 @end
30 
31 @implementation results
32 - (void)setCscore : (int)cScore
33 {
34     _cScore = cScore;
35 }
36 - (int)cScore
37 {
38     return _cScore;
39 }
40 
41 - (void)setOCscore : (int)OcScore
42 {
43     _ocScore = OcScore;
44 }
45 - (int)OcScore
46 {
47     return _ocScore;
48 }
49 
50 - (void)setSex : (Sex)sex
51 {
52     _sex = sex;
53 }
54 - (Sex)sex
55 {
56     return _sex;
57 }
58 
59 - (int)total
60 {
61     return  _cScore + _ocScore;
62 }
63 - (int)average
64 {
65     return (_cScore +  _ocScore )/2;
66 }
67 @end
68 int  main()
69 {
70    results *s = [results new];
71     [s setCscore : 80];
72     [s setOCscore : 100];
73     [s setSex : sexWomen];//写入一个性别
74     NSLog(@"%d	%d	%d",[s total],[s average],[s sex]);//get方法读取set写入数据
75     return 0;
76 }

面向对象的方式是对象的方法调用 

下面是类的方法调用

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface person : NSObject
 4 
 5 + (void)personClassName;
 6 @end
 7 
 8 @implementation person
 9 
10 + (void)personClassName
11 {
12     NSLog(@"person类,类方法调用");
13 }
14 
15 @end
16 
17 int main()
18 {
19     [person personClassName];
20 }
原文地址:https://www.cnblogs.com/zhangdashao/p/4438544.html