const static 在oc中的用法

本文讲解了在Objective-C中如何正确地使用static和const关键字来声明局部常量,特别是kAnimationDuration变量的作用域和不可变性,避免了链接错误并确保了动画持续时间的稳定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const表示不能修改  static表示作用域限定在本文件中

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

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

// EOCAnimatedView.m
#import "EOCAnimatedView.h"

static const NSTimeInterval kAnimationDuration = 0.3;

@implementation EOCAnimatedView
- (void)animate {
    [UIView animateWithDuration:kAnimationDuration
                     animations:^(){
                         // Perform animations
                     }];
}
@end

It is important that the variable is declared as both static and const. The const qualifier means that the compiler will throw an error if you try to alter the value. In this scenario, that’s exactly what is required. The value shouldn’t be allowed to change. The staticqualifier means that the variable is local to the translation unit in which it is defined. A translation unit is the input the compiler receives to generate one object file. In the case of Objective-C, this usually means that there is one translation unit per class: every implementation (.m) file. So in the preceding example, kAnimationDuration will be declared locally to the object file generated from EOCAnimatedView.m. If the variable were not declared static, the compiler would create an external symbol for it. If another translation unit also declared a variable with the same name, the linker would throw an error with a message similar to this:

duplicate symbol _kAnimationDuration in:
    EOCAnimatedView.o
    EOCOtherView.o

 

转载于:https://www.cnblogs.com/NSNULL/p/4489641.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值