gpt4 book ai didi

ios - 从 Objective C 中的另一个类访问变量值

转载 作者:行者123 更新时间:2023-11-28 18:32:28 24 4
gpt4 key购买 nike

A类.h

...
@property (weak, nonatomic) NSString *myVariable;
- (id) setMyVariable:(NSString *)string;
- (id) getMyVariable;

A类.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;
}

B类.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 上阅读了其他主题,但不知道为什么它不起作用。

最佳答案

你的整个代码真的有点乱。为什么要使用弱属性?你为什么要使用 @synthezise,因为这是由 xcode 自动为你完成的,还有 getter 和 setter,所以你永远不需要创建它们。

[classA getMyVariable];ClassC 中为 nil 的原因是因为您在上面的行中创建了它的新实例。从您要尝试做的事情来看,您想要为一个类中的类实例设置变量,并在不同类中的同一实例上访问该变量。所以这样做的一种方法是使用单例,这些有时不受欢迎,但我认为它们工作得很好并且没有看到一些(不是所有)开发人员不喜欢它们的原因。

所以让我们做一些清理并尝试实现一个单例

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]);
//........

如果您阅读 this 可能会有所帮助和 this帮助理解不同的设计模式

关于ios - 从 Objective C 中的另一个类访问变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25809488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com