在一个项目上工作时,我创建了一个类,我在另一个类中实例化(没什么特别的),但如果我尝试为这个实例调用一个方法,我得到这个:
由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [CALayer animate]:发送到实例的无法识别的选择器
这是班级.h:
#import <QuartzCore/QuartzCore.h>
@interface SFStripe : CALayer {
NSTimer *animation;
}
- (id)initWithXPosition:(NSInteger)positionX yPosition:(NSInteger)positionY;
- (id)initEndedWithXPosition:(NSInteger)positionX yPosition:(NSInteger)positionY;
- (void)animate;
- (void)reduceSize;
- (void)logSomething;
@property NSTimer *animation;
@end
这里是.m:
#import "SFStripe.h"
@implementation SFStripe
@synthesize animation;
- (id)initWithXPosition:(NSInteger)positionX yPosition:(NSInteger)positionY {
self = [CALayer layer];
self.backgroundColor = [UIColor blackColor].CGColor;
self.frame = CGRectMake(positionX, positionY, 5, 20);
self.cornerRadius = 5;
return self;
}
- (id)initEndedWithXPosition:(NSInteger)positionX yPosition:(NSInteger)positionY {
self = [CALayer layer];
self.backgroundColor = [UIColor grayColor].CGColor;
self.frame = CGRectMake(positionX, (positionY + 7.5), 5, 5);
self.cornerRadius = 2;
self.delegate = self;
return self;
}
- (void) logSomething {
NSLog(@"It did work!");
}
- (void)reduceSize {
if (self.frame.size.width > 0 && self.frame.size.height >= 5) {
self.frame = CGRectMake(self.frame.origin.x, (self.frame.origin.y - 0.5), self.frame.size.width, (self.frame.size.height - 0.5));
[self setNeedsDisplay];
NSLog(@"Width: %d", (int)self.frame.size.width);
NSLog(@"Height: %d", (int)self.frame.size.height);
} else {
self.backgroundColor = [UIColor grayColor].CGColor;
self.frame = CGRectMake(self.frame.origin.x, (self.frame.origin.y + 7.5), 5, 5);
[animation invalidate];
}
}
- (void)animate {
animation = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(reduceSize) userInfo:nil repeats:YES];
}
@end
我将这个类导入到一个新项目中,只是为了查看它是否在那里工作但是得到了同样的错误。这是我如何调用类的一个实例的方法之一(我得到所有方法的相同错误)
#import <UIKit/UIKit.h>
#import "SFStripe.h"
#import <QuartzCore/QuartzCore.h>
@interface STViewController : UIViewController {
SFStripe *stripe;
}
- (IBAction)animate:(id)sender;
@end
我创建了实例,在.m中我让动作调用实例的方法:
#import <QuartzCore/QuartzCore.h>
#import "STViewController.h"
#import "SFStripe.h"
@interface STViewController ()
@end
@implementation STViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
stripe = [[SFStripe alloc] initWithXPosition:30 yPosition:30];
[self.view.layer addSublayer:stripe];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)animate:(id)sender {
[stripe animate];
}
@end
抱歉所有的代码,但我找不到这个问题的答案,这有助于并希望有人可以帮助我!
答案 0 :(得分:0)
这不是编写初始化程序的正确方法:
- (id)initWithXPosition:(NSInteger)positionX yPosition:(NSInteger)positionY
{
self = [CALayer layer];
...
您将self
指定为普通的旧CALayer实例,而不是您的子类的实例。
改为使用self = [super init]
,然后检查self
是否为零。