我正在实现NSActionCell
(内部NSTableView
)的子类,并注意到一些不寻常的事情。如果我isEditing
在用户单击单元格时设置属性 ( ),则该属性的值会丢失,因为NSCell
此后不久就会释放。我认为发生这种情况是因为我没有正确处理复制,所以我添加了copyWithZone
. 现在我看到copyWithZone
被调用 - 但它是在一个意外的实例上调用的 - 并且该实例上的属性是NO
- 默认值。每次copyWithZone
调用时,都会在同一个实例上调用它。
任何人都可以阐明这种行为吗?我正在附加有问题的子类,以及我得到的输出。当用户单击不同的单元格时,我需要做什么才能保留单元格的属性?
@interface MyCell : NSActionCell <NSCoding, NSCopying>
{
}
@property (nonatomic, assign) BOOL isEditing;
@end
@implementation MyCell
- (id)init
{
if ((self = [super init]))
{
[self initializeCell];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super initWithCoder:aDecoder]))
{
[self initializeCell];
self.isEditing = [[aDecoder decodeObjectForKey:@"isEditing"] boolValue];
NSLog(@"initWithCoder %ld %i", (NSInteger)self, self.isEditing);
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[super encodeWithCoder: aCoder];
NSLog(@"encode %i", self.isEditing);
[aCoder encodeObject:[NSNumber numberWithBool:self.isEditing] forKey:@"isEditing"];
}
- (void)dealloc
{
NSLog(@"dealloc %ld %i", (NSInteger)self, self.isEditing);
[super dealloc];
}
- (id)copyWithZone:(NSZone *)zone
{
MyCell *copy;
if ((copy = [[MyCell allocWithZone:zone] init]))
{
copy.isEditing = self.isEditing;
}
NSLog(@"copy %ld %i new: %ld", (NSInteger)self, self.isEditing, (NSInteger)copy);
return copy;
}
- (void)initializeCell
{
self.isEditing = NO;
}
- (BOOL)startTrackingAt:(NSPoint)startPoint inView:(NSView *)controlView
{
return YES;
}
- (void)stopTracking:(NSPoint)lastPoint at:(NSPoint)stopPoint inView:(NSView *)controlView mouseIsUp:(BOOL)flag
{
if (flag)
{
self.isEditing = YES;
NSLog(@"stopTracking %ld %i", (NSInteger)self, self.isEditing);
}
}
@end
输出(当用户单击单元格时产生):
2012-11-21 08:17:59.544 SomeApp[2778:303] copy 4310435936 0 new: 4310152512
2012-11-21 08:18:00.136 SomeApp[2778:303] stopTracking 4310152512 1
2012-11-21 08:18:00.136 SomeApp[2778:303] dealloc 4310152512 1
再单击一次(在不同的单元格上):
2012-11-21 08:19:24.994 SomeApp[2778:303] copy 4310435936 0 new: 4310372672
2012-11-21 08:19:25.114 SomeApp[2778:303] stopTracking 4310372672 1
2012-11-21 08:19:25.114 SomeApp[2778:303] dealloc 4310372672 1