26

在尝试将我的模型与显示获取数据的视图控制器分离时,当异步获取完成时,我发布了一个 NSNotification。

 [[NSNotificationCenter defaultCenter] postNotificationName:@"foobarFetchSuccess" object: foo];

我已经养成了使用的习惯:

 #define FOO_FETCH_SUCCESS  @"foobarFetchSuccess"

在一个公共头文件中,然后将其用于 addObserver: 和 removeObserver: 以及 postNotificationName:

 [[NSNotificationCenter defaultCenter] addObserver:self @selector(gotData)
                                              name:FOO_FETCH_SUCCESS object: baz];

所以@"foobarFetchSuccess" 字符串被到处使用。还有更多像他一样的人。那么声明一个字符串并在任何地方使用它的最佳方法是什么?

4

2 回答 2

54

至于在项目中使用常量字符串,Stack Overflow 上还有另一个问题:Objective C 中的常量

至于命名通知,Cocoa 编码指南建议如下:

通知由全局 NSString 对象标识,其名称以这种方式组成:

[Name of associated class] + [Did | Will] + [UniquePartOfName] + Notification

于 2011-04-20T22:48:25.103 回答
3

这不完全遵循 Apple 建议的格式,也没有直接回答您的问题,但我想我会分享这些方便的花花公子的文本宏,我在制作通知和键名时使用这些宏来节省自己的一点打字时间。您可以为这些分配一个键盘快捷键,输入并选择[Did|Will] + [UniquePartOfName]段,然后点击快捷键以生成变量及其值。如果您在特定类的标题中定义这些字符串,您也可以使用$(FILENAMEASIDENTIFIER)而不是,这符合建议。$(PROJECTNAME)

//MARK: Notification strings
    { /*
       * Use the selection to make the name and string for a Notification.
       * The string has a prefix placeholder, defaulting to the project name.
       */
      Identifier = objc.notestring;
      BasedOn = objc;
      IsMenuItem = YES;
      Name = "Notification Name From Selection";
      TextString = "<#$(PROJECTNAME)#><#!notename!#>Notification = @\"<#$(PROJECTNAME)#><#!notename!#>Notification\";";
      CompletionPrefix = notestring;
    },
    { /*
       * Insert placeholders to make the name and string for a Notification.
       * This is for use without a selection, and so "only" activates at the 
       * beginning of the line.
       */
      Identifier = objc.notestring.bol;
      BasedOn = objc.notestring;
      IsMenuItem = YES;
      Name = "Notification Name From Selection";
      OnlyAtBOL = YES;
      CompletionPrefix = notestring;
    },

//MARK: Default Key strings
    { /*
       * Convert the selection into a name and string for use in the User 
       * Defaults system. The string has a placeholder for a prefix, which
       * defaults to the project name.
       */
      Identifier = objc.defaultskeystring;
      BasedOn = objc;
      IsMenuItem = YES;
      Name = "UserDefaults Key From Selection";
      OnlyAtBOL = NO;
      TextString = "<#$(PROJECTNAME)#><#!keyname!#>Key = @\"<#$(PROJECTNAME)#><#!keyname!#>Key\";";
      CompletionPrefix = defaultskey;
    },
    { /*
       * Insert placeholders to make the name and string for a a key for the
       * User Defaults system. This is for use without a selection, and so 
       * "only" activates at the beginning of the line.
       */
      Identifier = objc.defaultskeystring.bol;
      BasedOn = objc.defaultskeystring;
      IsMenuItem = YES;
      OnlyAtBOL = YES;
      Name = "UserDefaults Key From Selection";
      CompletionPrefix = defaultskey;
    },

这些是 Xcode 3 宏。我知道宏系统在 Xcode 4(我还没有使用)中有所不同,但我相信转换很简单并且可以自动化。

于 2011-04-20T23:46:00.373 回答