gpt4 book ai didi

objective-c - 模拟 NSString “enum” const 列表的最佳方法?

转载 作者:行者123 更新时间:2023-12-03 17:27:29 27 4
gpt4 key购买 nike

环境: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 的“enum”示例:
上传.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];

但是如何实现这一点呢?

最佳答案

我认为您提出的解决方案没有任何问题,但如果您不喜欢使用 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"

关于objective-c - 模拟 NSString “enum” const 列表的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141037/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com