user3191334
user3191334

Reputation: 1168

Objective C - Avoid Import Loop

I want to connect two classes of mine and link each other with a property of each class. I broke down the main aspects to this example:

Ocean.h file:

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

@interface Ocean : NSObject
@property (nonatomic) NSArray *listOfFishesInOcean;
@end

Fish.h file:

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

@interface Fish : NSObject
@property (nonatomic) Ocean *homeOcean;    // Compiler: "Unknown type name Ocean"
@property (nonatomic) int age;
@end

What I wanna do in the end, is to manipulate the age property of an Fish object and be able to save it (listOfFishesInOcean, NSUserDefaults), as well as call a function in the Ocean object, when saving is completed. This way I'd always have the latest list of Fish-objects in my list of the Ocean-object.

My two problems here are:

  1. How to avoid the import-loop, which causes the complier error, I think?
  2. How should I implement the save & action workflow in the end?

I thought about solving this issue with notifications and observer but this way I'd still need to filter the notifications in any way, due to the fact that I've multiple Oceans with more Fishes. Another idea to solve it, would be to give each Ocean object and Fish object an ID, which I would use as a key in NSUserDefaults again.

If anyone has some thoughts about it or other ideas, you are very welcome!

Upvotes: 3

Views: 458

Answers (2)

KSR
KSR

Reputation: 1709

Import ".h" files only in ".m" file, like:

Ocean.h file:

#import <Foundation/Foundation.h>
@class Fish;

@interface Ocean : NSObject
@property (nonatomic) NSArray *listOfFishesInOcean;
@end

Ocean.m file:

#import "Ocean.h"
#import "Fish.h"

 @implementation Ocean

@end

Fish.h file:

#import <Foundation/Foundation.h>
@class Ocean;

@interface Fish : NSObject
@property (nonatomic) Ocean *homeOcean;    
@property (nonatomic) int age;
@end

Fish.m file:

#import "Fish.h"
#import "Ocean.h"

 @implementation Fish

 @end

Upvotes: 1

Marco Santarossa
Marco Santarossa

Reputation: 4066

I think one of the best approaches could be using the identifiers so you improve the performance.

@interface Ocean : NSObject
@property (nonatomic) int identifier;
@property (nonatomic) NSArray *listOfFishesInOcean;
@end

@interface Fish : NSObject
@property (nonatomic) int age;
@property (nonatomic) int parent_identifier;
@end

if you want to keep your approach:

#import <Foundation/Foundation.h>
@class Ocean;

@interface Fish : NSObject
@property (nonatomic) Ocean *homeOcean;    // Compiler: "Unknown type name Ocean"
@property (nonatomic) int age;
@end

Fish.m

#import "Ocean.h"

Upvotes: 1

Related Questions