oc 第二讲 成员变量和方法

来源:互联网 发布:甘肃 预约挂号软件 编辑:程序博客网 时间:2024/05/14 07:08

#import “”导入自定义类,#import <>导入类库中的头文件。功能类似C语言中的#include,但是可以避免头文件被重复导入。容易出现循环导入问题。

解决方法:在 .h 头部加 @class 子类名,表示在这它表达的是类,在.m 中导入头文件,这样就能避免循环导入问题。

在定义类是我需要写成员变量,接下来就是第一点,什么是成员变量的可见度,什么意思呢?在定义成员变量时有3种可见度, 如图:

通常我们都是使用@protected,也就是不写,所有的运算都在方法里,例在.h 声明:

@protected                 //系统默认是@protected

 NSString *_pohto;

 NSString *_music;

   NSString *_video;

@public

   NSString *_size;

@private

   NSInteger _password;      //密码

   NSString *_id;

   NSString *_brand;

/// 自定义初始化

- (id)initWithSize:(NSString *)size password:(NSInteger)password;

/// 方法名: initWithSize:password:

//- (id)initWithSize:(NSString *)size :(NSInteger)password;

/// 方法名: initWithSize::

- (id)initWithBrand:(NSString *)brand video:(NSString *)video;

/// 查看密码

- (void)showPassword;

///  有参数,无返回值

- (void)setPassword:(NSInteger)password;

/// 获取密码

- (NSInteger)getPassword;

在.m 中

/// 初始化方法

- (id)init

{

   _password = 123456;

   return self;

}


/// 自定义初始化方法

- (id)initWithSize:(NSString *)size password:(NSInteger)password

{

    _size = size;

    _password = password;

    return self;

}


- (id)initWithBrand:(NSString *)brand video:(NSString *)video

{

    _brand = brand;

    _video = video;

    return self;

}


- (void)showPassword

{

    NSLog(@"密码是: %ld", _password);

}


/// 设置密码

- (void)setPassword:(NSInteger)password

{

   _password = password;

}


/// 获取密码

- (NSInteger)getPassword

{

    return _password;

}


在main 中运用

Phone *phone = [[Phone alloc] init];

        // @public修饰的成员变量

        phone->_size = @"4.0英寸";

        NSLog(@"这个手机的大小是%@", phone->_size);

        

        // @protected

        [phone showPassword];

        // 设置密码

        [phone setPassword:111111];

        [phone showPassword];

        // 手动输入得到密码

        long int a = 0;

        scanf("%ld", &a);

        [phone setPassword:a];

        [phone showPassword];

        

        //获取密码

        NSLog(@"获得密码: %ld",[phone getPassword]);

        //获取以后输出

        NSInteger pw = [phone getPassword];

        NSLog(@"获得密码: %ld", pw);


总结:@protected类,在得到所需要得值时 ,只能通过get方法在获取,不能在main 中直接用箭头指向:pw->password。这样是错误得,❌。


所以都要是用[pw getPassword]来实现我们想要得东西!

一般在写代码是我们都要使用@protected,受保护得。

0 0
原创粉丝点击