要在其他方法中访问的另一个类的Objective-C属性



大家好,我知道这个问题在这个论坛上被问了很多次。在浏览了这些帖子后,我确实从其中一篇帖子中找到了部分解决方案,但我对这篇帖子有一个疑问Objective-C:访问另一个类的属性。

我能够根据给定的答案访问属性的值,但不能在子类的其他实例方法中使用这些属性的相同值。有人能举例说明如何做同样的事吗。

附言:我确实理解,这是关于另一个帖子的一件非常基本的事情,因为我没有足够的声誉来评论我提出的这个问题,请帮助我,因为我在过去3天里遇到了这个问题,任何帮助都将不胜感激。

谢谢

代码更新

@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
}
}

我认为您可以使用singleton来创建单个实例,其他类可以使用相同的实例来访问属性。

例如:

+(id)singletonInstance
{
static classA *classA = nil;
static dispatch_oce_t onceToken;
dispatch_once(&onceToken, ^{
// if the instance is not there then create an instance and init one.
classA = [[self alloc] init];
});
return classA;
}

// in the same class .m file viewDidLoad add the below code
//classA.m
classA *classA = [classA sharedInstance]; // this will be the instance which will be called by other classes (i.e classB ..etc).

我已经测试了代码,它适用于任何查询,请回复我。

更改此

@property (nonatomic, weak) ClassA *classA;

@property (nonatomic, strong) ClassA *classA;

获得nil的原因是ClassA对象已解除分配。它被释放,因为弱引用没有保留它。只有强引用保留对象。阅读关于ARC.

ClassA实现更改为以下内容:

@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];
}
}
- (void)dealloc
{
// do you see this printed in console when you run the app?
NSLog(@"DEALLOC!!!");
}
@end

您的代码中有很多问题,请仔细检查代码。

我推断SomeSuperClass可能继承自UIViewController

1.初始化不返回实例对象

所有初始化方法都应该有一个返回值,您提供的代码没有返回值,应该改为这个

- (instancetype)init{
if (self = [super init]) {
_classB = [[ClassB alloc]initWithParent:self];
}
return self;
}

2.weak修饰符特性

通常,只有weak用于解决循环引用。在其他时间应避免使用,并在使用后立即释放。

3.someString属性未初始化

4.ClassAClassB的输入顺序

我假设您解决了前面的问题,顺序应该是先输入ClassA,然后输入ClassB

要从ClassA输入ClassB,必须使用初始化的classB属性,如以下

ClassA.m
[self.navigationController pushViewController:self.classB animated:YES];

最后在显示ClassB时执行viewDidLoad,可以得到正确的someString

最新更新