ClassA.h
...
@property (weak, nonatomic) NSString *myVariable;
- (id) setMyVariable:(NSString *)string;
- (id) getMyVariable;
ClassA.m
...
@synthezise myVariable = _myVariable;
... some inits
- (id) setMyVariable:(NSString *)string {
_myVariable = string;
NSLog(@"here nslog success return new value: ", _myVariable);
return _myVariable;
}
- (id) getMyVariable {
NSLog(@"here nslog return nil", _myVariable);
return _myVariable;
}
ClassB.m
#import ClassA.h
...
ClassA *classA = [[ClassA alloc] init];
[classA setMyVariable:@"some"];
ClassC.m
#import ClassA.h
...
ClassA *classA = [[ClassA alloc] init];
NSLog(@"here nslog returns nil: @%", [classA getMyVariable]);
[ClassC getMyVariable]
为什么返回nil?当我尝试在没有setter和getter的情况下直接设置值时,结果相同。我已经阅读了有关StackOverflow和Google的其他主题,但不知道它为什么不起作用。
答案 0 :(得分:4)
你的整个代码确实有点混乱。你为什么使用弱房产?为什么你使用的是@synthezise
,因为这是由xcode自动为你和getter和setter完成的,所以你不需要创建它们。
[classA getMyVariable];
中ClassC
为零的原因是因为您在上面的行中创建了它的新实例。通过你想要做的事情的外观,你想要在一个类中为一个类的实例设置变量,并在另一个类的同一个实例上访问该变量。所以这样做的一种方法是使用单身,这些有时候不受欢迎,但我认为它们运作良好,并且没有看到一些(不是所有)开发人员不喜欢它们的原因。
所以让我们做一些清理并尝试实现单例
<强> ClassA.h 强>
@interface ClassA : NSObject
@property (nonatomic, strong) NSString *myVariable;
// No need for you to create any getters or setters.
// This is the method we will call to get the shared instance of the class.
+ (id)sharedInstance;
@end
<强> ClassA.m 强>
#import "ClassA.h"
@implementation ClassA
// No need to add a @synthezise as this is automatically done by xcode for you.
+ (id)sharedInstance
{
static ClassA *sharedClassA = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// If there isn't already an instance created then alloc init one.
sharedClassA = [[self alloc] init];
});
// Return the sharedInstance of our class.
return sharedClassA;
}
@end
是的,我们已经清理了ClassA
代码并添加了一个方法来获取ClassA
的共享实例,现在转到ClassB
<强> ClassB.m 强>
// Other code in ClassB
// Get the shared instance
ClassA *classA = [ClassA sharedInstance];
// Set the value to the property on our instance.
[classA setMyVariable:@"Some String Value"];
//........
既然ClassB
设置了变量,我们现在可以转到ClassC
并查看它。
// Other code in ClassC
// We still need to have an instance of classA but we are getting the sharedInstance
// and not creating a new one.
ClassA *classA = [ClassA sharedInstance];
NSLog(@"My variable on my shared instance = %@", [classA myVariable]);
//........
答案 1 :(得分:1)
因为您在创建对象后未设置值。我应该是这样的:
ClassA *classA = [ClassA alloc] init];
[classA setMyVariable:@"some"];
NSLog(@"not nil anymore: @%", [classA getMyVariable]);
BTW:@property标签提供两个关键字来设置getter和setter方法。
@property (weak, nonatomic, getter=myVariable, setter=setMyVariable:) NSString *myVariable;
并且苹果在getter-methods中避免使用“get”这个词......