环境:Mac OS X 10.9,Xcode 5.0.2
我想为通知名称使用常量字段。像这样:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didUploadFinished)
name:uploadNotif_uploadFileFinished
object:nil];
我使用常量uploadNotif_uploadFileFinished
代替@"uploadNotif_uploadFileFinished"
。
常量字段代替@“string”给我们,在编译期间检查通知的名称。但实现这可能会有所不同。我使用extern常量或静态常量的found方法,参见下面的示例,但是可能存在更好的实现方法吗?
根据extern常量模拟NSString的“枚举”的示例:
Upload.h:
#import <Foundation/Foundation.h>
@interface Upload : NSObject <NSURLConnectionDelegate>
-(void)finishUpload;
@end
// Declaretion list name of notifications for Upload Objects. Enum strings:
// ________________________________________
extern NSString* const uploadNotif_uploadFileFinished;
extern NSString* const uploadNotif_uploadError;
// ________________________________________
Upload.m:
#import "Upload.h"
@implementation Upload
-(void)finishUpload
{
[[NSNotificationCenter defaultCenter]
postNotificationName:uploadNotif_uploadFileFinished object:nil];
}
@end
// Initialization list name of notifications for Upload Objects. Enum strings:
// ________________________________________
NSString* const uploadNotif_uploadFileFinished = @"uploadNotif_uploadFileFinished";
NSString* const uploadNotif_uploadError = @"uploadNotif_uploadError";
// ________________________________________
这个实现对我来说不是很喜欢,因为它不清楚在哪里声明“uploadNotif_uploadFileFinished”常量。理想的变体可能会像Upload::uploadFileFinished
:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didUploadFinished)
name:Upload::uploadFileFinished
object:nil];
但是怎么意识到这一点?
答案 0 :(得分:0)
我认为您提出的解决方案没有任何问题,但如果您不喜欢使用extern NSString* const
,则可以在标题中使用#define
这样的预处理器语句:
#define uploadNotif_uploadFileFinished @"uploadNotif_uploadFileFinished"
#define uploadNotif_uploadError @"uploadNotif_uploadError"
用法完全相同,只需导入标题即可使用常量。
就个人而言,我更喜欢定义extern NSString* const
。
修改强> 遗憾的是,Objective-C没有名称空间。广泛扩展的解决方案(甚至UIKit或Cocoa框架使用它)是在常量名称中使用您的类前缀。通过这种方式,您可以声明名称不会与其他框架声明名称冲突的常量。
例如:
#define JKUploadFileFinished @"uploadNotif_uploadFileFinished"
#define JKUploadError @"uploadNotif_uploadError"
答案 1 :(得分:-1)
你需要Objective-C ++;
h文件:
class Upload
{
public:
static NSString* const uploadFileFinished;
static NSString* const uploadError;
};
毫米-文件:
NSString* const Upload::uploadFileFinished = @"uploadNotif_uploadFileFinished";
NSString* const Upload::uploadError = @"uploadNotif_uploadError";