How to get a reference to the object that instantiated a second object in Objective-C?(如何获得对对象的引用,该对象实例化了Objective-C中的第二个对象?)
问题描述
A有一个对象(Second Object),它是NSObject的子类的实例,并且在Second Object中,我希望获取对实例化SecdObject的对象(FirstObject)的引用。
示例:
在FirstObject.m(UIView控制器的子类)中
SecondObject *secondObject = [[SecondObject alloc] init];
在Second对象中
@implementation SecondObject
- (id) init {
self = [super init];
NSLog(@"Parent object is of class: %@", [self.parent class]);
return self;
}
@end
我正在寻找与viewControlpers的.parentViewController属性类似的内容
我一直在研究KeyValueCoding,但没有找到解决方案。
我实现的解决方法是在secdObject.m中创建一个initWithParent:(ID)父方法,然后在实例化时传递self。
在Second对象中
@interface SecondObject ()
@property id parent;
@end
@implementation SecondObject
- (id) initWithParent:(id)parent {
self = [super init];
self.parent = parent;
NSLog(@"Parent object is of class: %@", [self.parent class]);
return self;
}
@end
,然后按如下方式实例化firtObject.m中的对象
SecondObject *secondObject = [[SecondObject alloc] initWithParent:self];
有没有更直接的方法?
Rgds...恩里克
推荐答案
对象没有任何类型的指向创建它的对象的指针。
您的initWithParent:方法将起作用,但您可能需要考虑为什么您的对象需要知道其创建者,以及是否没有更好的方法来完成您正在尝试完成的任何任务。
此外,您可能希望将Parent属性设置为弱属性,否则最终会到处创建保留周期。
这篇关于如何获得对对象的引用,该对象实例化了Objective-C中的第二个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获得对对象的引用,该对象实例化了Objective-C中的第二个对象?
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- Android viewpager检测滑动超出范围 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- android 4中的android RadioButton问题 2022-01-01