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

i1icjdpr  于 11个月前  发布在  iOS
关注(0)|答案(3)|浏览(81)

我知道这个问题在这个论坛上被问了很多次,在浏览了这些帖子之后,我确实从其中一个帖子中找到了问题的部分解决方案,但我对这个帖子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
    }
}

字符串

r6l8ljro

r6l8ljro1#

我认为你可以使用单例,它创建一个单一的示例,其他类可以使用相同的示例来访问属性。
例如:

+(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).

字符串

sg24os4d

sg24os4d2#

改变这种

@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

r8uurelv

r8uurelv3#

您的代码中有很多问题,请仔细检查代码。
我推断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

相关问题