1.封装
main.m
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
#pragma mark ----------封装---------------
/*
封装:隐藏内部的实现,稳定外部接口
好处:
使用起来更加简单
变量更加安全
可以隐藏内部实现细节
开发速度更加快捷
作用:
方法封装了具体实现的代码
属性封装实例变量
类封装了属性和方法
*/
NSString *name = @"Rick";
NSInteger age = 25;
NSString *homeAddress = @"GZ";
NSLog(@"Teacher names %@,%ld years old,living in %@",name,age,homeAddress);
Student *student = [[Student alloc]init];
//方法封装了具体实现的代码
[student helloWorld];
// [student hiGuys]; //私有方法不被外界所调用
}
return 0;
}
Student.h
#import <Foundation/Foundation.h>
//在OC中,几乎所有的类都继承于NSObject,剩下的都继承于NSProxy
@interface Student : NSObject
{
//使用类来封装变量
// NSString *_name;
// NSInteger _age;
// NSString *_homeAddress ;
}
//使用@property封装成员变量,实现变量的安全
@property (nonatomic,strong)NSString *name ;
@property (nonatomic,assign)NSInteger age ;
@property (nonatomic,strong)NSString *homeAddress;
-(void)helloWorld ;
@end
Student.m
#import "Student.h"
@implementation Student
-(id)init
{
if (self = [super init])
{
_name = @"Rick";
_age = 25;
_homeAddress = @"GZ";
}
return self;
}
//使用类来封装功能代码
-(void)helloWorld
{
//打印哪个类里面的哪个方法
NSLog(@"%s",__FUNCTION__);
NSLog(@"helloWorld!");
NSLog(@"Teacher names %@,%ld years old,living in %@",_name,_age,_homeAddress);
[self hiGuys];
}
//私有方法:在@interface中无相应声明方法,可以把他们看做私有方法,仅在类的实现中使用
-(void)hiGuys
{
NSLog(@"%s",__FUNCTION__);
NSLog(@"我是私有方法");
}
@end