Search code examples
objective-cweak-referencescircular-reference

Why the code does not work to avoid Circular References?


I am compiling code to avoid Retain Cycle, When I use weak , I got this error: 1. property of weak attribute must be of object type; 2. Unknown type name 'OrderEntry'. What is wrong with the code? Thanks!

// OrderEntry.h
#import <Foundation/Foundation.h>
#import "OrderItem.h"
#import "Address.h"

@interface OrderEntry : NSObject

 @property (strong, nonatomic)OrderItem *orderItem;
 @property (strong, nonatomic)Address *shippingAddress;
 @property (strong, nonatomic) NSString *orderID;

@end


// OrderItem.h
#import <Foundation/Foundation.h>
#import "OrderEntry.h"


@interface OrderItem : NSObject

 @property (strong,nonatomic) NSString *name;

 @property (weak, nonatomic) OrderEntry *entry;

 @end

Solution

  • The problem is with both .h files each including the other. This causes a circular dependency on the declarations. The simple solution is to use forward declarations instead.

    OrderEntry.h:

    #import <Foundation/Foundation.h>
    #import "Address.h"
    
    @class OrderItem;
    
    @interface OrderEntry : NSObject
    
     @property (strong, nonatomic) OrderItem *orderItem;
     @property (strong, nonatomic) Address *shippingAddress;
     @property (strong, nonatomic) NSString *orderID;
    
    @end
    

    OrderItem.h:

    #import <Foundation/Foundation.h>
    
    @class OrderEntry;
    
    @interface OrderItem : NSObject
    
     @property (strong, nonatomic) NSString *name;
     @property (weak, nonatomic) OrderEntry *entry;
    
    @end
    

    Then you import the .h files in the .m file.

    The general guideline is to import the fewest possible .h files in another .h file. Use forward declarations for classes and protocols whenever possible.