0

I have two custom NSObjects which reference each other, as below:

.h file class 1

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

@interface MyParentClass : NSObject

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

@end

.m file class 1:

#import "MyParentClass.h"

@implementation MyParentClass

@end

and...

.h file class 2:

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

@interface MyChildClass : NSObject

@property (nonatomic) MyParentClass *myParent;

@end

.m file class 2:

#import "MyChildClass.h"

@implementation MyChildClass

@end

When I try and implement those as below, the project will not build, with the error "Arc Restrictions: Implicit conversion of an Objective-C pointer to 'int *' is disallowed with ARC"

View Controller implementation code:

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

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

    newChild.myParent = newParent;

However, when I nest a second example into single .h/.m files, the project will build:

Nested .h file:

#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

Nested .m file:

#import "MyNestedClass.h"

@implementation MyChildNestedClass

@end

@implementation MyNestedClass

@end

I guess that by nesting the objects into a single file, I am somehow tricking ARC and that really I shouldn't be creating these circular references.

Could anyone suggest the correct way of nesting types like this?

What I am trying to achieve, is the following pseudo-scenario: Parent has a property of Child. Child has a property of the parent it is the child of.

Am I finding this difficult because I'm not supposed to do it (circular referencing), or am I missing something glaringly obvious?

Many thanks!

bdesham
  • 15,430
  • 13
  • 79
  • 123
Outy1812
  • 63
  • 6
  • FYI - You need to be sure that the child's reference to its parent is a `weak` reference. Otherwise you have some unwanted reference cycles. – rmaddy Jan 23 '15 at 16:46

1 Answers1

4

Do not #import "MyChildClass.h" in the parent class' header file, change it to

@class MyChildClass

and add the #import in the source file (.m)

Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59