ios Objective C 中的内存管理

发布于 2024-11-05 19:43:22 字数 968 浏览 0 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哥,最终变帅啦 2024-11-12 19:43:22

不,不存在泄漏,因为第一个数字是自动释放的对象。

No, there isn't a leak as first number is an autoreleased object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文