gpt4 book ai didi

objective-c - NSCell 的意外行为

转载 作者:行者123 更新时间:2023-12-03 17:55:58 25 4
gpt4 key购买 nike

我正在实现 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

最佳答案

听起来您想保留这些属性 - 是吗?

如果您通过将单元格属性存储在模型对象而不是 NSCell 中,并让单元格或 TableView 委托(delegate)从模型中获取值来调整设计,您可能会更轻松。

您试图使用此属性实现什么特定行为?

关于objective-c - NSCell 的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13497616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com