是否有可能反转财产的方向?(关于objective-c的语法)

是否有可能反转财产的方向?(关于objective-c的语法),objective-c,Objective C,有可能像逆方向走一样吗 [通常指财产的方向] @interface MainClass { CustomClass *test1; } @end @implementation MainClass self.test1 = [[CustomClass alloc] init]; @end [想知道财产的逆方向] @interface MainClass { CustomClass *test1; } @end @implementation MainClass

有可能像逆方向走一样吗

[通常指财产的方向]

@interface MainClass {
  CustomClass *test1;
 }
 @end

 @implementation MainClass
  self.test1 = [[CustomClass alloc] init];
 @end
[想知道财产的逆方向]

@interface MainClass {
  CustomClass *test1;
 }
 @end

 @implementation MainClass
  self.test1 = [[CustomClass alloc] init];
 @end
可以从test1向self指示吗

ex) like test1.myowner? or test1<-self? or test1/self or etc..

ex)比如test1.myowner?或者test1不,不是真的。无法从设置的对象与设置了属性的对象建立关联。您几乎肯定会想在
CustomClass
上声明一个属性,然后在
MainClass
的setter中,将
CustomClass
实例的属性设置为
self
否,属性是单向的。您必须显式定义一个反向属性并将其赋值


由于两个对象相互引用,还必须小心不要引入保留循环。只有一个属性必须保留/strong,否则,您将得到两个永远无法释放的对象。

这里有很多东西需要区分。首先,几乎所有声明的类都应该继承自
NSObject

@interface MainClass : NSObject {
您应该使用
@property
@synthesis
来创建实例变量,不要像您正在尝试的那样分配iVar。最好是这样写:

 @interface MainClass : NSObject 
 @property(nonatomic, retain) CustomClass *test1;
 @end

 @implementation MainClass
 @synthesize test1;

 // only if you're not using ARC
 -(void)dealloc {
     [test1 release];
     [super dealloc];
 }

 @end

比如test1.myowner?或者test1您可以自己实现这种行为,例如手动在setter方法中实现

- (void)setTest1:(CustomClass *)aCustomClass
{
    test1 = aCustomClass;
    test1.myowner = self;
}

当然,您必须将myowner属性添加到CustomClass中,并使其变弱或不安全,以避免循环retain循环。

考虑使用一些Obj-C运行时黑客来巧妙地解决此问题。这将是一个真正的方便。这通常出现在模型层代码中。核心数据可以自动管理这些类型的关系,以及其他许多事情。