ios Objective C 中的内存管理
我是 iOS 和 Objective-C 的新手,虽然我已经努力理解内存管理一段时间了,但我对自己很失望,因为我仍然需要全面了解......我的问题是我不明白如何保留对象的属性与保留整个对象有关。让我们以以下代码为例:
@interface TestObject:NSObject { //TestObject declaration
NSNumber *firstNumber;
}
@property (nonatomic, retain) NSNumber *firstNumber;
@end
@synthesize firstNumber;
-(void) dealloc //Use standard synthesized getter and setter, write only custom
//dealloc
{
[firstNumber release];
}
...以及使用它的以下代码:
-(IBAction) runClicked: (id) sender
{
TestObject *to1=[[TestObject alloc ] init];
to1.firstNumber=[NSNumber numberWithInt:10]; //retain count 1 on firstnumber
NSNumber *num=[to1.firstNumber retain]; //retain count 2 on firstnumber
[to1 release]; //retain count 1 on firstnumber because of 1 release in dealloc
}
我对代码进行了分析,并使用泄漏工具运行了程序,两者都没有发现泄漏。是否存在第一个数字(主对象释放后可通过 num 访问)泄漏,因为在 *num 在函数体末尾也被销毁后,任何指针都无法使用该数字?
非常感谢您抽出时间! 此致, 弗罗林.
I am new to iOS and objective-C and although I've been struggling for a while to understand memory management I am disappointed in myself because I still have to get the full picture... My problem is that I do not understand how retaining a property of an object relates with retaining the whole object. Let's take the following code as an example:
@interface TestObject:NSObject { //TestObject declaration
NSNumber *firstNumber;
}
@property (nonatomic, retain) NSNumber *firstNumber;
@end
@synthesize firstNumber;
-(void) dealloc //Use standard synthesized getter and setter, write only custom
//dealloc
{
[firstNumber release];
}
...and the following code that uses it:
-(IBAction) runClicked: (id) sender
{
TestObject *to1=[[TestObject alloc ] init];
to1.firstNumber=[NSNumber numberWithInt:10]; //retain count 1 on firstnumber
NSNumber *num=[to1.firstNumber retain]; //retain count 2 on firstnumber
[to1 release]; //retain count 1 on firstnumber because of 1 release in dealloc
}
I ran an analyze on the code and also ran the program with Leak instrument and no leaks were found by either. Isn't there a leak on firstnumber (accessible by num after main object release) since the number will not be usable by any pointer after *num is also destroyed at the end of function body?
Thank you so much for your time!
Best regards,
Florin.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,不存在泄漏,因为第一个数字是自动释放的对象。
No, there isn't a leak as first number is an autoreleased object.