Objective-C语言_面向对象(封装)
2015-12-16 13:54
555 查看
main.m
#import <Foundation/Foundation.h> #import "Student.h" int main(int argc, const charchar * 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
相关文章推荐
- setValue和setObject的区别
- Objective-C语言_点语法和@property
- Thymeleaf中的context对象-原标题:Context Objects in Thymeleaf
- Objective-C语言_便利初始化函数和便利构造器
- Objective-C_OC中的方法
- Objective-C语言-对象
- Objective-c语言_实例方法和类方法的区别
- 【web前端】typeof和object.toString.call()的区别
- Objective-c语言_可变字典
- Objective-c语言_不可变字典
- Objective-c语言_数组练习题2:
- Objective-c语言_数组练习题1
- Objective-C语言——NSMutableDictionary可变字典
- Objective-C语言——NSDictionary不可变字典
- Object-C 中各数据类型转换 NSData转NSString,Byte,UIImage
- object-c画笔的简单实现
- object-c画笔的简单实现
- Nullability and Objective-C
- Spring MVC 接收json自动转换JSONObject
- Object C中创建线程的方法有NSThread,GCD, NSOperation