不同的实例化方法
这之间有什么区别:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
后者会泄漏内存。 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.
好吧,它们或多或少会工作相同,因为您的第二个示例包含一个分配 (
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.