gpt4 book ai didi

iphone - 自动释放和属性

转载 作者:行者123 更新时间:2023-11-28 22:54:59 25 4
gpt4 key购买 nike

关于接下来的类(class),我有几个问题要问

#import <Cocoa/Cocoa.h>

@interface SomeObject {
NSString *title;
}

@property (retain) NSString *title;

@end




implementation SomeObject

@synthesize title;

-(id)init {
if (self=[super init])
{
self.title=[NSString stringWithFormat:@"allyouneed"];
}

return self;
}

-(void)testMethod{
self.title=[[NSString alloc] init] ;
}

-(void)dealloc {
self.title=nil;

[super dealloc];
}
  1. 在.h文件中添加属性时需要声明title和sub吗?添加 @property (retain) NSString *title 还不够吗?行。

2.我是否需要在 init 和 testMethod 中自动释放对标题的分配。那么为什么?

谁能给我解释一下这些事情。

最佳答案

1-您不需要在 header 中声明 iVar。您也可以使用

@synthesize myVar = _myVar;

如果您想使用不同的 iVar 名称

2-声明一个属性为“retain”意味着每次你为这个属性分配一个新的对象时,它会自动释放之前的对象并保留新的对象。

因此,如果您使用像 stringwithFormat 这样的便捷方法,该属性将为您保留该对象。

如果你想使用 alloc-init,对我来说最好的方法是:

NSString *str = [NSString alloc] init];
self.title = str;
[str release];

此外,在dealloc中给属性赋值nil是对的,因为属性会释放它拥有的对象,它调用retain on nil什么都不做

关于iphone - 自动释放和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11012092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com