我应该使用访问器方法还是直接访问iVars?:
- (id)initWithData: (NSData *)someData;
{
if (self = [super init]) {
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: someData];
[parser setDelegate: self];
[parser parse];
[parser release];
}
return self;
}
- (void)parser: (NSXMLParser *)parser didStartElement: (NSString *)elementName namespaceURI: (NSString *)namespaceURI qualifiedName: (NSString *)qName attributes: (NSDictionary *)attributeDict
{
[self setValue: someValue]; // Setting an iVar of self
[[self value] setOtherValue: otherValue]; // Setting an iVar of an object that's an iVar of self
}
答案 0 :(得分:0)
作为一般规则,我相信你应该这样做。在@property定义和一些较新的ARC内存管理问题出现之前,它可能更具争议性。但是,在头文件中使用诸如“@property(retain)”声明之类的内容确实有助于确保正确遵循保留/释放约定,甚至在ARC的情况下自动执行。
答案 1 :(得分:0)
除非你非常小心,否则不安全。想象一下以下场景:
@interface BaseClass : NSObject
@property (readwrite) NSInteger twists;
@end
@interface SubClass : BaseClass {
struct something *aField;
}
@end
@implementation BaseClass
- (id)init {
self = [super init];
if (self) {
self.twists = 100;
// or
[self setTwists:100];
}
return self;
}
@synthesize twists;
@end
@implementation SubClass
- (id)init {
self = [super init];
if (self) {
aField = malloc(sizeof(struct something));
}
return self;
}
- (void)dealloc {
free(aField);
[super dealloc];
}
- (void)setTwists:(NSInteger)value {
[super setTwists:value];
aField->twists++;
}
@end
如果使用SubClass
,则在实例化时将调用-setTwists:
的实现,这将取消引用aField
。那时,它的初始化程序没有执行;它的超类'初始化程序仍在执行中。程序将在NULL
指针取消引用时崩溃。