首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSCell的意外行为

NSCell的意外行为
EN

Stack Overflow用户
提问于 2012-11-22 00:24:34
回答 1查看 164关注 0票数 0

我正在实现NSActionCell的一个子类(在NSTableView中),并注意到一些不寻常的东西。如果我在用户单击单元格时设置了一个属性(isEditing),那么该属性的值就会丢失,因为NSCell很快就会被释放。我认为这是因为我没有正确处理复制,所以我添加了copyWithZone。现在我看到copyWithZone被调用了--但它是在一个意外的实例上被调用的--该实例上的属性是NO --默认值。每次调用copyWithZone时,都会在同一个实例上调用它。

有没有人能解释这种行为?我附加了有问题的子类,以及我得到的输出。当用户单击不同的单元格时,我到底需要做什么才能保留单元格的属性?

代码语言:javascript
复制
@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

输出(当用户单击单元格时产生):

代码语言:javascript
复制
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

然后再次单击(在不同的单元格上):

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2012-11-22 01:59:22

听起来你想持久化这些属性--是这样吗?

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13497616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档