我有一个类“TestA”,并将其对象放在主函数的 NSMutable 字典中。第二个名为“ThreadClass”的类有一个线程。在这个线程中,我从字典中获取对象并使用它。当我运行这个程序时,仪器向我显示了这个线程中的内存泄漏。但我不明白为什么内存泄漏,因为我没有使用任何新的或分配、复制或保留。我在主类中附加了我的程序的完整代码。需要有关内存管理的快速帮助。
我还有一个问题,如果我有一个以 NSString 作为数据成员的类。如果我将 this 的对象放在 NSMutabledictionary 中,那么我将如何处理它的内存管理。谢谢
#import <Cocoa/Cocoa.h>
@interface TestA : NSObject {
@public
NSString *strTemp1;
}
@end
#import "TestA.h"
/////////////////////////////////////////////
//Implementation class
@implementation TestA
-(id)init
{
self = [super init];
if (self != nil)
{
//strTemp1 = [[NSString alloc] init];
//printf("\n Temp 1 %d \n", [strTemp1 retainCount]);
}
return self;
}
@end
//Thread Class
#import <Cocoa/Cocoa.h>
#import "TestA.h"
@interface ThreadClass : NSObject {
}
@end
#import "ThreadClass.h"
extern NSMutableDictionary *clData;
@implementation ThreadClass
-(void)Initialize
{
[NSThread detachNewThreadSelector:@selector(AnimateThread:) toTarget:self withObject:nil];
printf("\n<<<<<<<<<<<<<<< Start Animator Thread Called >>>>>>>>>>>>>>>>>>>>>\n");
}
//==========================================================================
- (void) AnimateThread:(id) inObject
{
NSAutoreleasePool *Pool = [[NSAutoreleasePool alloc] init];
NSDate *timeToSleep = [NSDate dateWithTimeIntervalSinceNow:(NSTimeInterval)5];
while (1)
{
//NSAutoreleasePool *threadPool = [[NSAutoreleasePool alloc] init];
printf("\n Collection Size:%d \n", [clData count]);
TestA *obj1 = [clData objectForKey:@"abc"];
printf("\nThread Memory Counter:%d \n", [obj1 retainCount]);
printf("\nThread Memory Counter:%s \n", [obj1->strTemp1 UTF8String]);
//Sleep Thread for 5 Seconds
[timeToSleep release];
timeToSleep = [NSDate dateWithTimeIntervalSinceNow:(NSTimeInterval)5];
[NSThread sleepUntilDate:(NSDate *)timeToSleep];
//[timeToSleep release];
//[threadPool release];
}
[Pool release];
}
@end
//////////////////////////
Main Class
#import <Cocoa/Cocoa.h>
#import "TestA.h"
#import "ThreadClass.h"
NSMutableDictionary *clData = nil;
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
clData = [[NSMutableDictionary alloc] init];
//Creating Thread Class
ThreadClass *obj = [ThreadClass new];
[obj Initialize];
[obj release];
TestA *obj1 = [[TestA alloc] init];
NSString *strKey =[NSString new];
strKey = @"abc";
printf("\n Memory Counter:%d \n", [obj1 retainCount]);
printf("\n Memory Counter:%d \n", [obj1->strTemp1 retainCount]);
NSString *strTemp = @"Test Program";
obj1->strTemp1 = [NSString stringWithFormat:@"%s", [strTemp UTF8String]];
[obj1->strTemp1 retain];
printf("\n Memory Counter:%s \n", [obj1->strTemp1 UTF8String]);
[clData setObject:obj1 forKey:strKey];
printf("\nAfter Memory Counter:%d \n", [obj1 retainCount]);
printf("\nAfter Memory Counter:%d \n", [obj1->strTemp1 retainCount]);
[strKey release];
[obj1 release];
[pool release];
return NSApplicationMain(argc, (const char **) argv);
}