我想了解如何设置属性(访问器)的参数。
我从 Kal 日历的示例中获取了以下代码。
// Holiday.h
@interface Holiday : NSObject
{
NSDate *date;
NSString *name;
NSString *country;
}
@property (nonatomic, retain, readonly) NSDate *date;
@property (nonatomic, retain, readonly) NSString *name;
@property (nonatomic, retain, readonly) NSString *country;
- (id)initWithName:(NSString *)name country:(NSString *)country date:(NSDate *)date;
@end
// Holiday.m
#import "Holiday.h"
@implementation Holiday
@synthesize date, name, country;
- (id)initWithName:(NSString *)aName country:(NSString *)aCountry date:(NSDate *)aDate
{
if ((self = [super init])) {
name = [aName copy];
country = [aCountry copy];
date = [aDate retain];
}
return self;
}
- (void)dealloc
{
[date release];
[name release];
[country release];
[super dealloc];
}
@end
1) 属性设置为retain
,但由于不能使用 setter,所以retain
这里没有意义。
2) 此外,在initWithName
方法中,值是用 设置的copy
。为什么不直接copy
使用访问器方法定义属性?
@property (nonatomic, copy) NSString *name;
// ...
self.name = aName;
3)我需要readonly
这里吗?我不知道为什么在这里使用它们。如果我将copy
与 setter 一起使用,则readonly
禁止我设置值,因为没有 setter。
4)在initWithName
方法中有时copy
有时retain
使用。我建议总是copy
在这里使用,因为以后不应该修改该值。
5)我能记住的是,在方法中/中copy
是retain
可以的。initWithName
release
dealloc
那么你会如何建议使用retain
,copy
和readonly
在这个例子中呢?