iOS之变量定义使用

还是以例子来说明吧。新建一个ViewController类,Xcode为我们自动生成了两个文件:ViewController.h 和 ViewController.m

1、成员变量

@interface ViewController : UIViewController {
    // 我们称myTest1为成员变量
    BOOL myTest1;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    myTest1 = NO; // 不支持self.myTest1  或  [self myTest1] 的用法
}

@end

成员变量不使用 @synthesize,这个属性是私有属性,不断给它赋值时不会改变引用计数,

成员变量默认是protected,一般情况下,非子类对象无法访问。


2、类扩展的成员变量

@interface ViewController : UIViewController

@end

// 类扩展都是放在.m文件中@implementation的上方,否则会抱错
@interface ViewController () {
    // 类扩展的成员变量
    BOOL myTest2;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    myTest2 = YES; // 用法与1相同
}

@end

其实这种表达方式与1是一样的,区别在于更好的隐藏了.h文件的私有信息。

详见 点击打开链接


3、属性变量

@interface ViewController : UIViewController

// 属性变量,若不使用 @synthesize 只表示是public属性
@property (nonatomic, copy) NSString *str1;

@end

@implementation ViewController

@synthesize str1 = _str1; // 合成getter和setter,放在@implementation内

- (void)viewDidLoad {
    // 不存在的用法,直接报错
    str1 = @"abc";
    
    // 正确用法1
    _str1 = @"abc"; // 属性名加前_表示公有属性,在 @property 声明时系统会自己加

    // 正确用法2
    NSString *astr = [self str1];
    NSLog(@"%@", astr);

    // 正确用法3
    self.str1 = @"123";
}

@end

4、类扩展的成员变量

@interface ViewController : UIViewController

@end


@interface ViewController ()

   // 类扩展的属性变量
   @property (nonatomic, copy) NSString *str1;

@end

@implementation ViewController

   @synthesize str1 = _str1; // 没意义

- (void)viewDidLoad {
    // 错误的用法
    str1 = @"345";
    
    // 正确用法
    self.str1 = @"123";
    
    // 正确用法
    _str1 = @"678";
    
    // 正确用法
    NSString * aStr = [self str1];
}

@end

没有@synthesize其实作用一样,因为str1没有经过.h对开公开。类扩展中定义的@property的作用无非是使用self.str1 和 [self  str1]  更方便些。


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

#import "ViewController.h"

@implementation ViewController {
    NSString *str2; // 也是成员变量,只是放在@implemetation中的变量无法被子类继承 
}

// 报错
@synthesize str2 = _str2;

- (void)viewDidLoad {
    // 正确用法
    str2 = @"234";
    
    // 报错
    _str2 = @"345";
    
    
    // 报错
    self.str2 = @"";
    
}

@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值