Sno*_*man 1 cocoa-touch objective-c ios
我经常需要访问我的核心数据管理对象上下文,而不是[[UIApplication sharedApplication] delegate]
每次在每个类中获取一个实例并将其存储在变量中,我想知道是否可以这样做:
@interface NSObject(DelegateExtension)
- (AppDelegate*)appDelegate;
@end
@implementation
NSObject(DelegateExtension)
- (AppDelegate*)appDelegate
{
return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}
@end
Run Code Online (Sandbox Code Playgroud)
所以我可以self.appDelegate
在我的代码中的任何地方做.
做到这一点有什么不妥,可能一夜之间显而易见吗?这是不好的编程习惯吗?
或者,您可以在文件中添加预处理器宏(或静态C函数)Prefix.pch
:
#define AppDelegateInstance() (AppDelegate *)[[UIApplication sharedApplication] delegate]
Run Code Online (Sandbox Code Playgroud)
这将使您的应用程序委托可以从代码中的任何位置访问,并且不存在与任何现有方法冲突的可能性appDelegate
.
归档时间: |
|
查看次数: |
2300 次 |
最近记录: |