我正在學習Objective-C並使用Big Nerd Ranch的Obj-C書來熟悉這門語言。到目前爲止,一切都很順利,直到我完成這一個練習,我應該創建2個班級,每個班級都繼承了dealloc
方法。當對象實際被釋放時顯示的目標。因此,新的dealloc看起來像Objective-C:dealloc沒有被調用
Asset.h
#import <Foundation/Foundation.h>
@class Employee;
@interface Asset : NSObject{
NSString * label;
unsigned int resaleValue;
}
@property (strong) NSString * label;
@property unsigned int resaleValue;
@end
Employee.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
的main.m
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]
以及?
該代碼應該使用ARC還是手動內存管理? – UIAdam 2012-04-24 16:56:42
那麼我可以回答旁註問題:-)既然你好像在使用ARC,那麼[超級dealloc]就會被ARC添加到你的dealloc方法中。 – bas 2012-04-24 16:57:56