【发布时间】:2014-01-15 15:10:25
【问题描述】:
环境: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” 给我们,在编译期间检查通知的名称。 但是实现这可能会有所不同。我是found 使用外部常量或静态常量的方法,请参见下面的示例,但也许存在更好的实现方式?
基于外部常量模拟 NSString 的“枚举”的示例:
上传.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;
// ________________________________________
上传.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];
但是如何实现呢?
【问题讨论】:
-
就我而言,您回答了自己的问题。不要将
#define用于对象,您将在各处创建不必要的对象。而且你不需要需要 Objective-C++,它们是独立的全局变量并没有错(毕竟这是C)。我建议直接使用FOUNDATION_EXPORT而不是extern,因为FOUNDATION_EXPORT映射到extern或extern 'C',这取决于哪个是合适的(从Objective-C 到Objective-C++ 的无思想迁移)
标签: objective-c cocoa initialization constants