【发布时间】:2010-10-28 15:02:31
【问题描述】:
我想了解如何设置属性(访问器)的参数。
我从 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,但由于无法使用设置器,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?
【问题讨论】:
标签: iphone objective-c properties initialization accessor