【问题标题】:Method is expected to return an instance of its class type方法应返回其类类型的实例
【发布时间】:2015-09-16 17:07:08
【问题描述】:

我有一个NSTimer,它从类方法中调用以控制NSProgressBar。它表面上看起来很好,虽然我在使用 NSTimer 时收到警告,我假设编译器需要类名。

当我用类名MyProgressBar 代替NSTimer 时,警告似乎消失了。事情的现实是,所有的地狱都在幕后爆发,内存分配开始飙升。

问题是,这到底应该怎么做?

.h

@interface MyProgressBar : NSProgressIndicator {
    double progressOffset;
    NSTimer* animated;
}

@property (readwrite, retain) NSTimer* animated;
@property (readwrite) double progressOffset;

.m

- (void)setDoubleValue:(double)value {
    [super setDoubleValue:value];
    if (![self isDisplayedWhenStopped] && value == [self maxValue]) {
        [self stopAnimation:self];
    }
}

- (NSTimer*)animated {   // This is the line with the warning 
    return animated;    // using MyProgressBar ends up creating a memory leak
}

- (void)setAnimated :(NSTimer *)value {
    if (animated != value) {
        [animated invalidate];
        animated = value;
    }
}

- (id)initWithFrame :(NSRect)frameRect {
    self = [super initWithFrame:frameRect];
    if (self) {
        self.progressOffset = 0;
        self.animated = nil;
    }
    return self;
}

警告:

Method is expected to return an instance of its class type 'MyProgressBar', but is declared to return 'NSTimer *'
Overridden method returns an instance of its class type

->complete github project here that displays the warning.

【问题讨论】:

    标签: objective-c xcode macos class nstimer


    【解决方案1】:

    getter 应该被称为animated,而不是animate

    此外,您应该在所有实例变量中使用下划线(默认模式)并删除 getter/setter,因为编译器将提供更好的实现(即 setAnimated 看起来不正确,如果我记得使用手册引用计数)。 getter 应该返回一个 autoreleased 对象。

    【讨论】:

    • 是的,这是我的错字,我的意思是动画。不过还是同样的问题-谢谢。这样做的原始方式确实像你提到的那样发布了它,尽管因为它现在是 ARC,我认为它是不行的。 Here's the original method.
    • 好吧,我会放弃你的 getter/setter 实现;他们坏了。
    • @RoryZipher 见this 答案。
    • 有什么需要特别注意的吗?
    • 他们在解释什么是有道理的,我认为使用类名(MyProgressBar *) 代替(NSTimer *) 并删除invalidate would been the right way,但显然它远非如此.我不知道如何用它做一个autoreleased 对象......
    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多