我知道这个问题在这个论坛上被问了很多次,在浏览了这些帖子之后,我确实从其中一个帖子中找到了问题的部分解决方案,但我对这个帖子Objective-C: Accessing a property of another class有一个疑问。
我能够通过给定的答案访问属性的值,但不能在子类的其他示例方法中使用这些属性的相同值。有人能给出一些例子来说明如何做到这一点吗?
代码更新
@interface ClassA : SomeSuperClass
@property (some Attributes) ClassB *classB;
@property (some Attributes) NSString *someString;
@end
@implementation
-(id)init {
if (self = [super init]) {
_classB = [[ClassB alloc]initWithParent:self];
}
}
@end
@class ClassA;
@interface ClassB : SomeSuperClass
@property (nonatomic, weak) ClassA *classA;
-(id)initWithParent:(ClassA*)parent;
@end
#import "ClassA.h"
@implementation
-(void)viewDidLoad{
NSLog(@"%@",self.classA.someString); //here I get null
}
-(id)initWithParent:(ClassA*)parent {
if (self = [super init]) {
_classA = parent;
NSLog(@"%@", self.classA.someString); //perfectly legal and prints the string value
}
}
字符串
3条答案
按热度按时间r6l8ljro1#
我认为你可以使用单例,它创建一个单一的示例,其他类可以使用相同的示例来访问属性。
例如:
字符串
sg24os4d2#
改变这种
字符串
到
型
你得到nil的原因是因为
ClassA
对象被释放了。它被释放是因为你的弱引用没有保留它。只有强引用保留对象。阅读ARC。将
ClassA
实现更改为以下内容:型
r8uurelv3#
您的代码中有很多问题,请仔细检查代码。
我推断
SomeSuperClass
可能继承自UIViewController
1.示例不返回示例对象
所有的初始化方法都应该有一个返回值,你提供的代码没有返回值,你应该改成这个
字符串
2.
weak
修饰符属性一般只使用
weak
来解决循环引用,其他时候应该避免使用,使用后会立即发布。3.
someString
属性看不到初始化4.
ClassA
和ClassB
进入的顺序我假设你已经解决了前面的问题,顺序应该是先输入
ClassA
,然后输入ClassB
。要从
ClassA
输入ClassB
,必须使用初始化的classB
属性,如下所示型
最后在显示
ClassB
时执行viewDidLoad
,可以得到正确的someString