新建一个打印类 初始化代码如下
@implementation Print
-(id)init{
self = [super init];
if (self) { [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(print) userInfo:nil repeats:YES];
//每隔一秒 打印一次
}
}
-(void)print{
NSLog(@"=========================");
}@end@implementation PrintViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self AutoPrint];
}
-(void)AutoPrint{
Print *p = [[Print alloc] init];
//生成P对象
}-(void)StopPrint{// 想要在这里释放p对象,从内存里清除,代码应该怎么写?
}
@end
@implementation Print
-(id)init{
self = [super init];
if (self) { [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(print) userInfo:nil repeats:YES];
//每隔一秒 打印一次
}
}
-(void)print{
NSLog(@"=========================");
}@end@implementation PrintViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self AutoPrint];
}
-(void)AutoPrint{
Print *p = [[Print alloc] init];
//生成P对象
}-(void)StopPrint{// 想要在这里释放p对象,从内存里清除,代码应该怎么写?
}
@end
把PRINT类声明在PrintViewController中, 在StopPrint中把p置为NULL不就行了
所以你的这句语句
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(print) userInfo:nil repeats:YES];
会让NSTimer对self的计数器加1,所以你的p不会被释放,直到你的NSTimer计时器被显式的设置无效.
也就是你要调用[NSTimer invalidate]才会释放p,就象5楼说的