iPhone内存管理
家人好 我有一个关于iPhone内存管理的问题 我所理解的是下面的方法iPhone内存管理,iphone,objective-c,memory-management,Iphone,Objective C,Memory Management,家人好 我有一个关于iPhone内存管理的问题 我所理解的是下面的方法 -(void) dealloc { // something else to release whatever // such as Object Created using keyword 'alloc' // but also Object destroy here its retain value reaches iff 0 // if I do put here NSLog(@"%d"
-(void) dealloc
{
// something else to release whatever
// such as Object Created using keyword 'alloc'
// but also Object destroy here its retain value reaches iff 0
// if I do put here NSLog(@"%d", [obj retainCount]); and when it reaches
// not equal to 0 means failure with memory leak.
[super dealloc];
}
那么我理解的对吗?或者即使此处的保留计数达到>0,它仍然点亮
我问这个问题的原因是
我和他核实过了
NSLog(@"%d", obj.retainCount);
检查对象的保留计数和接收值3。所以我试着在这里释放了3次,使这里的retainCount等于0,但编译器给了我严重的错误
求你了,我是新的内存分配和保留,释放
我使用的对象是“UIImageView”对象,并创建了另一个实例
UIImageView *imageView = //da da~ with UIImage
UIImageView *instance;
// at this point retain count was '1'
instance = imageView;
//[imageView retain];
// at this point retain count was '2'
[self.view addSubView: imageView];
// at this point retain count was '3'
[imageView release];// crashes
// at this point retain count was '2'
但如果我这样做了
// but if I add retain on the 'instance = imageView'
// such as
instance = imageView; // then
[imageView retain];
// works but still count is 2...
谢谢。
retainCount
不是一个可靠的调试工具:
- 其他对象可能仍然包含对
obj
- 有些东西是你无法摧毁的(例如)
- 如果在保留计数为1的情况下释放对象,则会取消分配
- 用适当数量的
/release
autorelease
- 使用
- 使用
retainCount
不是可靠的调试工具:
- 其他对象可能仍然包含对
obj
- 有些东西是你无法摧毁的(例如)
- 如果在保留计数为1的情况下释放对象,则会取消分配
- 用适当数量的
/release
autorelease
- 使用
- 使用
- 这是不正确的,您应该很少使用retainCount。此时不必为0,因为其他对象可以引用您正在释放的对象。在dealloc中,重要的是释放您拥有所有权的对象。哪些是使用alloc或new等创建的对象。这是不正确的,您应该很少使用retainCount。此时不必为0,因为其他对象可以引用您正在释放的对象。在dealloc中,重要的是释放您拥有所有权的对象。哪些是使用alloc或new等创建的对象。覆盖dealloc的正常过程是释放此实例先前保留(或分配)的任何对象
因此,如果您在对象中的其他地方调用了alloc或retain方法,您的dealloc将如下所示:
-(void)someOtherMethod
{
UIImageView *imageView = //da da~ with UIImage
UIImageView *instance;
instance = imageView;
[instance retain];
}
-(void) dealloc
{
//release any retained objects here
[instance release]
[super dealloc];
}
请注意,在您的特定发布之后,如果发布计数没有下降到零,这并不重要,这只是意味着其他一些代码位也保留了对象内存(而其他一些代码位将负责释放它)
希望这能有所帮助。覆盖dealloc的正常过程是释放此实例先前保留(或分配)的任何对象 因此,如果您在对象中的其他地方调用了alloc或retain方法,您的dealloc将如下所示:
-(void)someOtherMethod
{
UIImageView *imageView = //da da~ with UIImage
UIImageView *instance;
instance = imageView;
[instance retain];
}
-(void) dealloc
{
//release any retained objects here
[instance release]
[super dealloc];
}
请注意,在您的特定发布之后,如果发布计数没有下降到零,这并不重要,这只是意味着其他一些代码位也保留了对象内存(而其他一些代码位将负责释放它)
希望这有帮助