我确信这是一个简单的,但到目前为止它是难以捉摸的,我很难过......
如何声明Ivar以便可以从项目中的所有类访问它?
[不知道它是否重要,但有问题的ivar是我的Model类的一个实例,其数据需要可供各种视图控制器访问.
从Objective-C 2.0编程语言中的"实例变量的范围"可以看出最好的 ...这将是使用"@public"指令.
所以我在声明了ivar的@interface块中尝试了这个:
@interface ...
...
@public
ModelClass *theModel;
@end
Run Code Online (Sandbox Code Playgroud)
...但是当我尝试在另一个类中引用"theModel"时,编译器不会自动完成,当我无论如何键入它时,编译器显示:"错误:'theModel'未声明(首先使用于这个功能)".
我认为这是一个Scope的问题,我没有适当地提供ivar,但是如何?不知何故,我需要访问它,或以某种方式使其指针可用.
任何想法都会非常感激.非常感谢!
也许您忘了将实例变量放在所有实例变量声明所在的类的大括号内?
@interface Foo : NSObject {
// other instance variable declarations
@public
ModelClass *theModel;
}
// method and property declarations
@end
Run Code Online (Sandbox Code Playgroud)
另外,您能否向我们展示您如何尝试从其他地方访问实例变量的代码?正确的语法应该是:
myFooInstance->theModel
Run Code Online (Sandbox Code Playgroud)
其中myFooInstance是" Foo *" 的类型值
我通过代表我的数据模型的单例使属性可用于由选项卡栏管理的所有视图。这是高效的,并且允许所有视图访问数据(以及任何其他应用程序元素)。创建单例非常简单(SO 上有大量示例)。您只需请求实例并获取所需的属性值。
这是创建单例的框架。关键点是静态实例以及您作为 进行初始化的事实[[self alloc] init];。这将确保对象得到正确清理。类底部的所有方法都是 SDK 文档中的标准方法,以确保忽略释放调用(因为该对象是全局共享的)。
单例样板(ApplicationSettings.m):
static ApplicationSettings *sharedApplicationSettings = nil;
+ (ApplicationSettings*) getSharedApplicationSettings
{
@synchronized(self) {
if (sharedApplicationSettings == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedApplicationSettings;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedApplicationSettings == nil) {
sharedApplicationSettings = [super allocWithZone:zone];
return sharedApplicationSettings; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4735 次 |
| 最近记录: |