在尝试从显示提取数据的视图控制器中取消模型时,异步提取完成后,我发布了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”字符串遍布整个地方。还有更多像他一样的人。 那么,一旦声明一个字符串并在任何地方使用它的最佳方法是什么?
答案 0 :(得分:54)
至于在项目中使用常量字符串,还有关于Stack Overflow的另一个问题:Constants in Objective C。
至于命名通知,Coding Guidelines for Cocoa建议如下:
通知由全局NSString对象标识,其名称以这种方式组成:
[Name of associated class] + [Did | Will] + [UniquePartOfName] + Notification
答案 1 :(得分: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中的宏系统是不同的(我还没有使用),但我相信转换很简单,可以自动化。