OC 封装

2018-06-17  本文已影响6人  CaptainRoy
封装就是把一个类的相关属性不能直接暴露给外部,或直接通过属性赋值,通过函数来对类的属性数据进行操作

一般情况通过setter和getter方法来进行操作
在oc中@property自动生成setter和getter方法进行调用

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property(nonatomic,copy)NSString *name; // 姓名
@property(nonatomic,assign)NSUInteger age; // 年龄
@property(nonatomic,copy)NSString *sex; // 性别

// 初始化
-(Person *)initWithName:(NSString *)name andAge:(NSUInteger)age andSex:(NSString *)sex;

// 自我介绍
-(void)introduce;

// 跑步
-(void)run;

@end
#import "Person.h"

@implementation Person

-(instancetype)init
{
    if ([super init]) {
        NSLog(@"%s",__FUNCTION__);
    }
    return self;
}

-(Person *)initWithName:(NSString *)name andAge:(NSUInteger)age andSex:(NSString *)sex
{
    NSLog(@"%s",__FUNCTION__);
    self = [super init];
    if (self) {
        _name = [name copy];
        _age = age;
        _sex = [sex copy];
    }
    return self;
}

-(void)introduce
{
    NSLog(@"我的名字: %@ , 性别: %@ , 年龄: %lu",self.name,self.sex,(unsigned long)self.age);
}

-(void)run
{
    NSLog(@"%@ 在跑步",self.name);
}

@end
Person *p = [[Person alloc] init]; // -[Person init]
NSLog(@"p: %@",p); // p: <Person: 0x100400430>
Person *roy = [[Person alloc] initWithName:@"roy" andAge:18 andSex:@"男"]; // -[Person initWithName:andAge:andSex:]
[roy introduce]; // 我的名字: roy , 性别: 男 , 年龄: 18
[roy run]; // roy 在跑步
上一篇 下一篇

猜你喜欢

热点阅读