前言
例如,有一个Person类:
#import <Foundation/Foundation.h>
#import “Book.h”
@interface Person : NSObject
@property(nonatomic,retain)NSString *name;
@property(nonatomic,retain)Book *book;
@end
#import “Person.h”
@implementation Person
– (void)dealloc
{
NSLog(@“人挂了。。。”);
[_name release];
[_book release];
[super dealloc];
}
@end
还有一个Book类:
#import <Foundation/Foundation.h>
@interface Book : NSObject
/// 书名
@property(nonatomic,retain)NSString *name;
///作者名字
@property(nonatomic,retain)NSString *authorName;
///传播知识的方法
– (void)castZhiShi;
@end
#import “Book.h”
@implementation Book
– (void)dealloc
{
NSLog(@“书被烧了。。。”);
[_name release];
[_authorName release];
[super dealloc];
}
– (void)castZhiShi
{
NSLog(@“书中自有黄金屋,书中自有颜如玉。。。”);
}
@end
一、当两个类相互包含的时候,当Person.h当中包含Book.h,而Book.h中又包含Person.h,这个时候,就会出现循环引用的问题造成无限递归的问题,而导致无法编译通过。。。
二、解决方案
1.当两个类相互包含的时候,其中1个类,不要用#import引用,而是用@class Book,这句话什么意思呢,表明这个Book是一个类,解决方案:其中1边不要使用#import引入对方的头文件,而是使用@class 类名;,来标注这是1个类,这样子就可以在不引入对方头文件的情况下,告诉编译器,这是1个类
2.@class与#import的区别
1)#import是将指定的文件的内容拷贝到写指令的地方
2)@class 并不会拷贝任何内容,它只是告诉编译器,这是1个类,这样编译器在编译的时候,才可以知道这是1个类
总结:这种写法,唯一的缺点是,它不会提示,这时候,在Person.m文件中,再#import "Book.h"就可以了,例如:
#import <Foundation/Foundation.h>
@class Book;
@interface Person : NSObject
@property(nonatomic,retain)NSString *name;
@property(nonatomic,retain)Book *book;
///人的读书的方法
- (void)read;
@end
#import “Person.h”
#import “Book.h”
@implementation Person
- (void)dealloc
{
NSLog(@“人挂了。。。”);
[_name release];
[_book release];
[super dealloc];
} - (void)read
{
//1.让自己拥有的书传播知识
[_book castZhiShi];
//2.自己吸收
NSLog(@“啊,好知识。。。”);
}
@end
#import <Foundation/Foundation.h>
#import “Person.h”
@interface Book : NSObject
/// 书名
@property(nonatomic,retain)NSString *name;
///作者名字
@property(nonatomic,retain)NSString *authorName;
//书有一个拥有者
@property(nonatomic,retain)Person *owner;
///传播知识的方法
- (void)castZhiShi;
@end
#import “Book.h”
@implementation Book
- (void)dealloc
{
NSLog(@“书被烧了。。。”);
[_name release];
[_authorName release];
[_owner release];
[super dealloc];
} - (void)castZhiShi
{
NSLog(@“书中自有黄金屋,书中自有颜如玉。。。”);
}
@end
#import <Foundation/Foundation.h>
#import “Book.h”
int main(int argc, const char * argv[]) {
Person *p1 = [Person new];
Book *b1 = [Book new];
p1.book = b1;
[p1 read];
[b1 release];
[p1 release];
return 0;
}