【问题标题】:objective c circular reference [duplicate]目标c循环引用[重复]
【发布时间】:2015-01-23 16:39:44
【问题描述】:

我有两个相互引用的自定义 NSObject,如下所示:

.h 文件类 1

#import <Foundation/Foundation.h>
#import "MyChildClass.h"

@interface MyParentClass : NSObject

@property (nonatomic, strong) NSString *Name;
@property (nonatomic) MyChildClass *myChild;

@end

.m 文件类 1:

#import "MyParentClass.h"

@implementation MyParentClass

@end

还有……

.h 文件类 2:

#import <Foundation/Foundation.h>
#import "MyParentClass.h"

@interface MyChildClass : NSObject

@property (nonatomic) MyParentClass *myParent;

@end

.m 文件类 2:

#import "MyChildClass.h"

@implementation MyChildClass

@end

当我尝试实现以下这些时,项目将无法构建,并出现错误“Arc Restrictions: Implicit conversion of an Objective-C pointer to 'int *' is notallowed with ARC”

查看控制器实现代码:

    MyParentClass *newParent = [[MyParentClass alloc] init];
    MyChildClass *newChild = [[MyChildClass alloc] init];

    newParent.Name = @"Johnny";
    newParent.myChild = newChild;

    newChild.myParent = newParent;

但是,当我将第二个示例嵌套到单个 .h/.m 文件中时,项目将构建:

嵌套 .h 文件:

#import <Foundation/Foundation.h>

@class MyNestedClass;

@interface MyChildNestedClass : NSObject

@property (nonatomic, strong) MyNestedClass *myNested;
@property (nonatomic, strong) NSString *ChildName;

@end

@interface MyNestedClass : NSObject

@property (nonatomic, strong) MyChildNestedClass *myChild;
@property (nonatomic, strong) NSString *ParentName;

@end

嵌套 .m 文件:

#import "MyNestedClass.h"

@implementation MyChildNestedClass

@end

@implementation MyNestedClass

@end

我猜想通过将对象嵌套到单个文件中,我以某种方式欺骗了 ARC,而且我真的不应该创建这些循环引用。

谁能提出正确的嵌套类型的方法?

我想要实现的是以下伪场景:Parent 具有 Child 的属性。 Child 具有作为其子级的父级的属性。

我觉得这很困难,因为我不应该这样做(循环引用),还是我错过了一些明显的东西?

非常感谢!

【问题讨论】:

  • 仅供参考 - 您需要确保子代对其父代的引用是 weak 引用。否则你会有一些不需要的参考周期。

标签: ios objective-c


【解决方案1】:

不要在父类的头文件中#import "MyChildClass.h",改成

@class MyChildClass

并在源文件 (.m) 中添加#import

【讨论】:

  • .h 都不应该导入另一个 .h。两者都应该使用前向声明。
猜你喜欢
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 2021-11-02
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多