main.m文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"
int
main()
{
Person *p = [[Person alloc] init];
Dog *d = [[Dog alloc] init];
p.dog = d;
d.person = p;
return
0;
}
|
Dog.m文件:
1
2
3
4
5
6
7
8
|
#import "Dog.h"
@implementation Dog
- (
void
)dealloc
{
NSLog(@
"Dog--dealloc"
);
}
@end
|
Person.m文件:
1
2
3
4
5
6
7
8
9
10
|
#import "Person.h"
@implementation Person
- (
void
)dealloc
{
NSLog(@
"Person--dealloc"
);
}
@end
|
1
2
3
4
5
6
7
8
9
|
#import <Foundation/Foundation.h>
@
class
Person;
@interface Dog : NSObject
@property (nonatomic,strong) Person *person;
@end
|
Person.h文件:
1
2
3
4
5
6
7
8
9
|
#import <Foundation/Foundation.h>
@
class
Dog;
@interface Person : NSObject
@property (nonatomic, strong) Dog *dog;
@end
|
对于上述main.m文件中红色部分“人养一条狗,狗有一个主人”,仔根据两个.h文件中部分,编译运行时会出现“人strong狗,狗strong人”的情况,导致p和d占用的内存无法被回收,即上图黄色部分不打印。解决办法为:
一端用strong,另一端用weak
比如可以将Dog.h文件中strong改成weak,就可以解决循环strong 问题。