1、MRC
Person.h
#import <Foundation/Foundation.h>
#import "Dog.h"
NS_ASSUME_NONNULL_BEGIN
@interface Person : NSObject
{
Dog *_dog;
}
- (void)setDog:(Dog *)dog;
- (Dog *)dog;
@end
NS_ASSUME_NONNULL_END
Person.m
#import "Person.h"
@implementation Person
- (void)setDog:(Dog *)dog {
if (_dog != dog) {
[_dog release];
_dog = [dog retain];
}
}
- (Dog *)dog {
return _dog;
}
- (void)dealloc {
[_dog release];
_dog = nil;
NSLog(@"%s",__func__);
[super dealloc];
}
@end
调用
int main(int argc, const char * argv[]) {
@autoreleasepool {
Dog *dog = [[Dog alloc] init];
Person *person = [[Person alloc] init];
[person setDog:dog];
[dog release];
[person setDog:dog];
[person release];
}
return 0;
}