我正在实现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
答案 0 :(得分:1)
听起来你想坚持这些属性 - 是吗?
如果通过在模型对象而不是NSCell中存储单元格属性来调整设计,并且让单元格或表格视图委托从模型中获取值,则可能会更容易。
您尝试使用此属性实现了哪些特定行为?