Ios 从不同的类访问类变量
这是一个非常普遍的问题,但似乎每个人对访问属于另一个类的变量都有自己的看法。我想要的是在class2中使用布尔变量来执行语句。我想要的例子是:Ios 从不同的类访问类变量,ios,objective-c,xcode,scope,Ios,Objective C,Xcode,Scope,这是一个非常普遍的问题,但似乎每个人对访问属于另一个类的变量都有自己的看法。我想要的是在class2中使用布尔变量来执行语句。我想要的例子是: Class1.h @Interface Class1{ bool boolean; } @Property (nonatomic, retain) bool boolean; Class1.m @synthesize boolean; Class2.m if(class1.boolean == YES){ Do Something }
Class1.h
@Interface Class1{
bool boolean;
}
@Property (nonatomic, retain) bool boolean;
Class1.m
@synthesize boolean;
Class2.m
if(class1.boolean == YES){
Do Something
}
if语句is class2似乎不起作用,因为我试图在class2中打印布尔值,但它返回的结果都是false。我想获取class1布尔变量的当前值,并在类2中使用它,而无需对其进行初始化。查看您的问题,您似乎想在另一个类中创建“
class1
”的实例,获取要在其中显示的属性值
在这种情况下,无论何时实例化“Class1
”,它都带有初始值。这意味着值肯定是'null
'。如果您想获得更改后的值,需要将“Class1
”创建为Singleton类,其中,该类将在整个应用程序中实例化一次。意味着在任何类中更改“boolean1
”的值,并在其他类中获得相同的值,无论何时何地
但是,这完全取决于你想如何使用整个东西
单例示例:
// Class1.h
@interface Class1 : NSObject
/**
* A boolean property
*/
@property (nonatomic, strong) BOOL *boolean;
// Class1.m
@implementation Class1
// This is actual initialisation of the class instance.
+ (Class1 *)sharedInstance {
static Class1 *sharedInstance = nil; //static property, so that it can hold the changed value
// Check if the class instance is nil.
if (!sharedInstance) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// If nil, create the instance, using dispatch_once, so that this instance never be created again. So, if needed, app will use the existing instance.
sharedInstance = [[super allocWithZone:NULL] init];
// custom initialisation if needed
});
}
return sharedInstance;
}
// So that, if somebody uses alloc and init, a new instance not created always.
// Rather use existing instance
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
// So that, if somebody uses alloc and init, a new instance not created always.
// Rather use existing instance
- (id)copyWithZone:(NSZone *)zone {
return self;
}
@end
现在更新并使用该值
//Class2.m
#import "Class1.h"
Class1 *myinstance = [[Class1 alloc] init];
myinstance.boolean = YES;
获取另一个类的值
//Class3.m
#import "Class1.h"
Class1 *myinstance = [[Class1 alloc] init];
if(myinstance.boolean == YES){
Do Something
}
你的问题令人困惑。将
NSLog()
周围的其余代码显示为“is null”目前对我来说意义不大。你的问题有点模糊。你能给出一个简单的代码示例来说明你面临的问题或你不清楚的部分吗?最后,是什么让你认为“每个人对访问属于另一个类的变量都有自己的看法”?输出BOOL tryNSLog(@“Boolean Value is:%d”,(int)self.Boolean)对不起,如果我不清楚,我更新了整个问题谢谢你的时间。你能简单地解释一下Class1.m实现中发生了什么吗?我正在编辑我的答案并添加注释。请给我一些时间。问题,class1必须是NSObject类型吗?这取决于你想在singleton类中继承什么。但对于基本功能,“NSObject”是必须的。因为NSObject是根类,所以我发现最好的方法是使用方法返回变量。这是访问变量当前值的唯一方法\