What is the compound relationship of has a relationship between objects in Objective-C
This article will explain in detail what is the compound relationship of has a relationship between objects in Objective-C. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
What is a compound relationship?
The compound relationship of a class is one of the most common relationships of a class.
Composition is the relationship of has a, such as the Person class contains a member attribute, Book object, Person has a Book.
The realization of compound relationship
OC requires that all objects are referenced as pointers, so this relationship should be reflected as follows:
The object of the Person class contains the address of a Book object.
As shown in the figure, it contains three objects:
Person object (created by the new method)
NSString object (literal value of string object @ "Zhang San" assignment)
Book object (created by the new method)
Memory condition of compound relationship
Obviously, the p pointer must be a local variable in a function or method, and its memory uses stack controls.
All the objects in Objective-C must be in the heap, so the memory of the three objects Person, NSString and Book is heap space.
The memory space of Person, NSString and Book is not continuous or mutually contained.
Person has a NSString represents the address of the NSString object in the Person object
Person has a Book represents the address of the Book object in the Person object
Circular reference problem
If the attributes in two classes are combined with each other, the header files contain each other and there will be circular references.
Using @ class in the header file declares the composite class. This problem can be solved by including the header file of the class in the source file.
/ / AMPerson.h@class AMBook;@interface AMPerson: NSObject {AMBook * book;} @ end//AMPerson.m#import "AMBook.h" @ implementation AMPerson /... @ end//AMBook.h@class AMPerson;@interface AMBook: NSObject {AMPerson * person } @ end//AMBook.h#import "AMPerson.h" @ implementation AMBook / /... @ end so much about the compound relationship of has a relationships between objects in Objective-C. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.