OBJC中声明字符串常量的一个常见错误
2013-07-10 19:04
267 查看
我们知道,NSNotification是Cocoa中观察模式最易用的实现方法,比起直接使用KVO(Key-Value Observing)他更加容易实现也更好理解。一个样例:
注意到,在使用Notifikation的时候,会需要声明字符串常量,作为notification的name。这时,const的位置就比较重要,很容易让不了解的人犯错误:
错误的写法(常量指针):
正确的写法(指针常量):
这里涉及到常量指针和指针常量的概念,简单的来说:
常量指针:就是指向常量的指针,关键字 const 出现在 * 左边,表示指针所指向的地址的内容是不可修改的,但指针自身可变。
指针常量:指针自身是一个常量,关键字 const 出现在 * 右边,表示指针自身不可变,但其指向的地址的内容是可以被修改的。
在此例中:我们知道,NSString永远是immutable的,所以NSString * const 是有效的,而const NSString * 则是无效的。而使用错误的写法,则无法阻止修改该指针指向的地址,使得本应该是常量的值能被修改,造成了隐患。这是需要注意的一个常见错误。
lancy
原文链接:http://gracelancy.com/?p=379
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
相关文章推荐
- OBJC中声明字符串常量的一个常见错误
- OBJC中声明字符串常量的一个常见错误
- OBJC中声明字符串常量的一个常见错误(常量指针和指针常量)
- 一个不常见的内存溢出错误
- 一个常见的错误pthread_create()的参数
- 一个常见的asp.net错误解决
- 黑马程序员----objective-C 类与对象基础篇(二)【声明与实现,方法与函数及常见错误】
- 一个常见数据库操作错误的分析(五)
- vs2005入门 之 变量的概念\声明\特性\常见错误 [视频]
- List集合的一个常见错误
- 一个奇葩常见的问题 nginx 403 forbidden错误
- UITableView 的一个常见错误'unable to dequeue a cell with identifier Cell - must register a nib or a class f
- python中tkinter中新手一个常见的错误
- 一个低级的常见错误
- 使用svm的一个常见错误
- 一个因xdata声明引起的隐含错误
- 这个是一个常见错误
- Makefile 的一个常见错误
- 深入理解闭包系列第四篇——常见的一个循环和闭包的错误详解
- 数据中心管理常见错误,犯一个就是致命的