使用@synthesize时使用哪种方法是正确的

mag*_*nus 1 iphone ios4

在合成属性方面我有点困惑.

让我们说我的*.h文件中有这个属性.

@property (nonatomic, retain) NSString *aString;
Run Code Online (Sandbox Code Playgroud)

在我的*.m文件中我合成它.@synthesize aString;

我知道当我使用synthesize时,编译器将生成setter和getter.但这些孵化器和吸气器是怎样的?

当我给aString一个值时,哪些方法是正确的?

self.aString = @"My New String"; // This will use the setter?
aString = @"My new String"; //This will not use the setter and retain the string, right?
aString = [@"My new string" retain]; //This will not use the setter, but it will retain the string ?
[self setAString:@"My new string"]; //This will also use the setter?
Run Code Online (Sandbox Code Playgroud)

提前致谢!

aro*_*oth 5

当你这样做时:

@property (nonatomic, retain) NSString *aString;
Run Code Online (Sandbox Code Playgroud)

...其次是:

@synthesize aString;
Run Code Online (Sandbox Code Playgroud)

......你的班级有三个基本的东西:

  1. 一个名为的实例变量aString,可以在类中直接引用.
  2. 具有签名的getter函数,- (NSString*) aString;用于返回实例变量.
  3. 具有签名的setter函数,该签名- (void) setAString: (NSString*) value;保留传入的参数并将其分配给实例变量(并释放任何先前保留的值,如果存在的话);

在实现方面,这些生成的方法和字段可能如下所示:

//in the .h file
@interface MyClass {
    NSString* aString;
}

- (NSString*) aString;
- (void) setAString: (NSString*) value;

@end


//in the .m file
@implementation MyClass

- (NSString*) aString {
    return aString;
}

- (void) setAString: (NSString*) value {
    if (aString != value) {
        [aString release];
        aString = [value retain];
    }
}

@end
Run Code Online (Sandbox Code Playgroud)

所以回答你的其余问题:

self.aString = @"My New String"; // This will use the setter?  Yes, and it will retain the string.
aString = @"My new String"; //This will not use the setter and retain the string, right?  Right.
aString = [@"My new string" retain]; //This will not use the setter, but it will retain the string?  Right again.
[self setAString:@"My new string"]; //This will also use the setter?  Yep.
Run Code Online (Sandbox Code Playgroud)

至于哪些是正确的,它们都是,取决于你想要什么,并假设你理解使用每一个之间的行为有何不同,特别是在释放/保留属性值方面.例如,此代码将泄漏内存:

self.aString = @"Value 1";  //go through the setter, which retains the string
aString = @"Value 2";        //bypass the setter, the 'Value 1' string will not be released
Run Code Online (Sandbox Code Playgroud)

......而这个等效代码不会:

self.aString = @"Value 1";  //go through the setter, which retains the string
self.aString = @"Value 2";  //go through the setter again to release the first string
Run Code Online (Sandbox Code Playgroud)