您的位置:首页 > 职场人生

黑马程序员——OC三大特性之封装

2014-09-21 12:43 381 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

封装:隐藏内部细节,提高安全性

<span style="font-size:18px;">#import <Foundation/Foundation.h>
@interface Student : NSObject
{
// 不能直接访问age要通过方法setAge访问,为了有范围  以后尽量不能写@public
int age;
}
/* 提供一个方法,给外界纯粹用来设置(age)属性的,称为set方法
可以再方法里面对参数进行过滤,如果想要数据“只写”,可只写一个set方法(不常用)
1、方法名必须以set开头
2、set后跟上成员变量的名称,成员变量的首字母必须大写
3、返回值一定是void
4、一定要接收一个参数,而且参数类型跟成员变量一致
5、形参的名称不能跟成员变量名一样
*/</span>
<span style="font-size:18px;">
/*
没有了@public还要想在main函数中直接访问stu->age则要使用get方法
get 方法   (如果要数据只读  ,只提供get方法)
1、作用,返回对象内部的成员变量。保证内部数据的安全。
2、命名规范
肯定有返回值,返回值类型肯定与成员变量类型一致
方法名跟成员变量名一样
不需要接收任何参数

*/</span>
<span style="font-size:18px;">
- (void)setAge:(int)newAge;   // set函数
- (int)age;                // get函数
- (void)study;
@end

@implementation Student
- (void)setAge:(int)newAge
{
if(newAge <= 0)
{
newAge = 1;
}
age = newAge;
}

- (int)age
{
return age;
}

- (void)study
{
NSLog(@"%d的人在学习", age);
}
@end

int main()
{
Student *stu =[Student new];

[stu setAge:0];
NSLog(@"学生的年龄是%d岁", [stu age]);  // 此age是get函数中的age。输出1岁
[stu study];  <span style="white-space:pre">				</span>// 输出1岁的
return 0;
}</span>


成员变量的命名规范:

<span style="font-size:18px;">#import <Foundation/Foundation.h>

typedef enum{
SexMan,
SexWoman
} Sex;
@interface Student : NSObject
{
/* 成员命名规范:一定要以下划线 _ 开头
作用:1、让成员变量和get方法的名称区分开 2、可以跟局部变量区分开,下划线开头的变量一般是成员变量 */

int _no;
Sex _sex;
}
- (void)setSex:(Sex)sex; // sex的set函数
- (Sex)sex; // sex的get函数
- (void)setNo:(int)no;
- (int)no;
@end
@implementation Student
- (void)setSex:(Sex)sex
{

_sex = sex;
}
- (Sex)sex
{
return _sex;
}
- (void)setNo:(int)no
{
_no = no;
}
- (int)no
{
return _no;
}

@end

int main()
{
Student *stu = [Student new];
[stu setSex:SexMan];
[stu setNo:10];
[stu sex];
[stu no];

return 0;
}</span><span style="font-size:24px;">
</span>

封装练习:

设计一个成绩类:

C语言成绩(可读可写)、oc成绩(可读可写)、总分(只读)、平均分(只读)

#import <Foundation/Foundation.h>
@interface Score : NSObject
{
int _cScore; // c成绩
int _ocScore; // oc成绩
int _totalScore;   // 总分
int _avergeScore;   // 平均分

}
// c成绩的set和get方法
- (void)setCScore:(int)cScore;
- (int)cScore;
// oc成绩的set和get方法

- (void)setOcScore:(int)cScore;
- (int)ocScore;
- (int)totalScore;
- (int)avergeScore;

@end

@implementation Score

- (void)setCScore:(int)cScore           // 封装此方法可以监听变量改变
{
_cScore = cScore;
<span style="white-space:pre">	</span>// 计算总分
_totalScore = _cScore + _OcScore;
_avergeScore = _totalScore/2;
}
- (int)cScore
{
return  _cScore;
}
- (void)setOcScore:(int)cScore
{
_ocScore = ocScore;
_totalScore = _cScore + _OcScore;
_avergeScore = _totalScore/2;
}
- (int)ocScore
{
renturn _ocScore;
}
- (int)totalScore
{
return _totalScore;
}
- (int)avergeScore
{
return _avergeScore;
}

@end

int main()
{
Score *s = [Score ne
4000
w];
[s setCScore];
[s setOcScore];
int a = [s totalScore];
int b = [s avergeScore];
NSLog(@"总分是%d", _totalScore);
NSLog(@"平均分是%d", _avergeScore);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: