OBJC中声明字符串常量的一个常见错误

我们知道,NSNotification是Cocoa中观察模式最易用的实现方法,比起直接使用KVO(Key-Value Observing)他更加容易实现也更好理解。一个样例:

Poster.h
// Define a string constant for the notification
extern NSString * const PosterDidSomethingNotification;
Poster.m
NSString * const PosterDidSomethingNotification = @”PosterDidSomethingNotification”;
...
// Include the poster as the object in the notification
[[NSNotificationCenter defaultCenter]
postNotificationName:PosterDidSomethingNotification
              object:self];
Observer.m
// Import Poster.h to get the string constant
#import “Poster.h”
...
// Register to receive a notification
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(posterDidSomething:) 
                                             name:PosterDidSomethingNotification 
                                           object:nil];
...
- (void) posterDidSomething:(NSNotification *)note {
    // Handle the notification here
}
- (void)dealloc {
    // Always remove your observations
    [[NSNotificationCenter defaultCenter]
    removeObserver:self];
    [super dealloc];
}

注意到,在使用Notifikation的时候,会需要声明字符串常量,作为notification的name。这时,const的位置就比较重要,很容易让不了解的人犯错误:

错误的写法(常量指针):

extern const NSString * RNFooDidCompleteNotification;

正确的写法(指针常量):

extern NSString * const RNFooDidCompleteNotification;

这里涉及到常量指针和指针常量的概念,简单的来说:

  • 常量指针:就是指向常量的指针,关键字 const 出现在 * 左边,表示指针所指向的地址的内容是不可修改的,但指针自身可变。
  • 指针常量:指针自身是一个常量,关键字 const 出现在 * 右边,表示指针自身不可变,但其指向的地址的内容是可以被修改的。

在此例中:我们知道,NSString永远是immutable的,所以NSString * const 是有效的,而const NSString * 则是无效的。而使用错误的写法,则无法阻止修改该指针指向的地址,使得本应该是常量的值能被修改,造成了隐患。这是需要注意的一个常见错误。

lancy

原文链接:http://gracelancy.com/?p=379

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值