不同的实例化方法

发布于 2024-11-04 08:38:24 字数 503 浏览 0 评论 0原文

这之间有什么区别:

AppDelegate *appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];

bookmarkObject *bookmark = (bookmarkObject *)[appDelegate.bookmarks objectAtIndex:i];

   AppDelegate *appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];

    bookmarkObject *bookmark = [[bookmarkObject alloc]init];
    bookmark = [appDelegate.bookmarks objectAtIndex:i];

如果我不明白,这是一个大问题吗 两者都有效,但我不明白有什么区别

What is the difference between this:

AppDelegate *appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];

bookmarkObject *bookmark = (bookmarkObject *)[appDelegate.bookmarks objectAtIndex:i];

And

   AppDelegate *appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];

    bookmarkObject *bookmark = [[bookmarkObject alloc]init];
    bookmark = [appDelegate.bookmarks objectAtIndex:i];

Does it is a big problem if I don't get it? Both work but I don't get the difference

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

与往事干杯 2024-11-11 08:38:24

后者会泄漏内存。 objectAtIndex 返回一个自动释放的对象。在第二个示例中,您泄漏了 alloc 分配的内存。

正确的是第一个。如果您正在讨论实例化,那么通常有三种方法,一种是 [NSArray alloc] init],另一个是 [NSArray array] - 这是 [[[NSArray alloc] init] autorelease] 和 [array] 的快捷方式copy] 创建一个副本。在所有情况下,除了自动释放的情况外,您必须自己释放内存。
Objective-C 是围绕传递指针构建的。因此,如果有某种方法返回指针,则无需分配或初始化任何内容。一般的经验法则 - 无论谁分配内存,都应该负责释放,否则必须自动释放。

The latter leaks memory. The objectAtIndex returns a auto-released object. In the second example you leak the memory allocated by alloc.

The proper one is the first. If you're discussing instantiation, then there're usually three methods, one, like [NSArray alloc] init], another [NSArray array] - which is a shortcut to [[[NSArray alloc] init] autorelease] and the [array copy] which creates a copy. In all cases, but autoreleased ones you have to release memory yourself.
Objective-C is built around passing pointers. Therefor if there's some method then returns pointer, you don't have to allocate or init anything. And a general rule of thumb - whoever allocates the memory, should be responsible for releasing, or it must be autoreleased.

瑾夏年华 2024-11-11 08:38:24

好吧,它们或多或少会工作相同,因为您的第二个示例包含一个分配 (bookmark = [[bookmarkObject alloc] init]),该分配立即被第二个分配 (mookmark = [appDelegate.bookmarks objectAtIndex:i];)。

但第二个会泄漏内存。

Well, they would work the same, more or less, since your second example contains an assignment (bookmark = [[bookmarkObject alloc] init]) that is immediately overruled by the second assignment (mookmark = [appDelegate.bookmarks objectAtIndex:i];).

The second one leaks memory, though.

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