我正在学习 Objective-C 并使用 Big Nerd Ranch 的 Obj-C 书来熟悉该语言。到目前为止一切都很好,直到我完成了这个练习,我应该在其中创建 2 个类,其中每个类都继承了该dealloc
方法。显示对象何时真正被释放的目标。所以新的 dealloc 看起来像
资产.h
#import <Foundation/Foundation.h>
@class Employee;
@interface Asset : NSObject{
NSString * label;
unsigned int resaleValue;
}
@property (strong) NSString * label;
@property unsigned int resaleValue;
@end
员工.h
#import "Person.h"
@class Asset;
@interface Employee : Person
{
int employeeID;
NSString * lastName;
Person * spouse;
NSMutableArray * children;
NSMutableArray * assets;
}
@property int employeeID;
- (void) addAssetObject: (Asset *) a;
- (unsigned int) valueOfAssets;
@end
实现
@implementation Employee
//omitted
-(void) dealloc
{
NSLog(@"deallocating %@", self);
}
@end
@implementation Asset
//omitted
-(void) dealloc
{
NSLog(@"deallocating %@", self);
}
@end
主文件
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray * employees = [[NSMutableArray alloc] init];
for(int i = 0; i< 10; i++){
Employee * person = [[Employee alloc] init];
[person setWeightInKilos:90+i];
[person setHeightInMeters:1.8 - i/10.0];
[person setEmployeeID:i];
[employees addObject:person];
}
for(int i = 0; i< 10; i++){
Asset * asset = [[Asset alloc] init];
NSString * currentLabel = [NSString stringWithFormat:@"Laptop %d", i];
[asset setLabel:currentLabel];
[asset setResaleValue:i*17];
NSUInteger * randomIndex = random() % [employees count];
Employee * randomEmployee = [employees objectAtIndex:randomIndex];
[randomEmployee addAssetObject:asset];
}
NSLog(@"Employees: %@", employees);
NSLog(@"Giving up ownership of one employee");
[employees removeObjectAtIndex:5]; // This is supposed to trigger the deallocate method
NSLog(@"Giving up ownership of array");
employees = nil;
}
return 0;
}
当然description
已经被继承了,这样%@
就可以了。但是,当我运行它时。没有调用 dealloc,也没有得到释放对象的打印输出。我不确定我在这里做错了什么。
旁注:dealloc不应该也这样做[super dealloc]
吗?