iOS资料汇总iOS 易混淆的点iOS技术专题

Objective-C 预处理 static const ext

2016-05-25  本文已影响1128人  FaiChou

作者:周辉
All rights reserved.

多用类型常量,少用 #define 预处理指令


const

const最好理解,修饰的东西不能被修改
指针类型根据位置的不同可以理解成3种情况:

  1. 常量指针
// 初始化之后不能赋值,指向的对象可以是任意对象,对象可变。
NSString *const pt1;
  1. 指向常量的指针
// 初始化之后可以赋值,即指向别的常量,指针本身的值可以修改,指向的值不能修改
const NSString *pt2;
  1. 指向常量的常量指针
const NSString * const pt3;

extern

全局变量的定义

//x .h 声明
extern const NSString *AA;
//x .m 定义
const NSString *AA = @"abc";
// 调用
#import "x.h"
// 或者再次申明
extern const NSString *AA;

static

static 关键字对变量的作用域进行了限制,使得变量仅在源文件内有效。


static 与 const 结合

// 声明一个静态的全局只读常量
static const int a = 20;
// 开发中经常拿到key修改值,因此用const修饰key,表示key只读,不允许修改
static NSString * const key = @"name";

// 如果 const修饰 *key1,表示*key1只读,key1还是能改变
static NSString const *key1 = @"name";

一般用法

// FCAnimatedView.h
#import <UIKit/UIKit.h>

@interface FCAnimatedView : UIView
- (void)animate;
@end

// FCAnimatedView.m
#import "FCAnimatedView.h"

static const NSTimeInterval kAnimationDuration = 0.3;

@implementation FCAnimatedView
- (void)animate {
    [UIViewanimateWithDuration:kAnimationDuration
                               animations:^() {
                                      //  Perform animations
                               }];
}

上一篇下一篇

猜你喜欢

热点阅读