Ger*_*and 2 objective-c automatic-ref-counting
我有一个类方法的类看起来像:
+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
self = [[self alloc] initWithTitle:title target:target action:action];
return self;
}
Run Code Online (Sandbox Code Playgroud)
它适用于手动引用计数,但是当我尝试将它与ARC一起使用时,我得到错误:"无法在类方法中分配给self".有没有办法解决这个问题?
我认为这与ARC无关.不同的是,使用ARC时,编译器会为此提供警告/错误.
通常在类方法(以+而不是 - 以不同方式调用的方法)中,self不引用特定对象.它指的是班级.使用[self alloc],无论是否为子类,都可以创建该类的对象.如果这是一个实例方法[[self class] alloc]将完全相同.但是你有充分的理由在课堂上.
你为什么不在这种情况下返回结果呢?
+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
return [[self alloc] initWithTitle:title target:target action:action];
}
Run Code Online (Sandbox Code Playgroud)
如果您的班级名称是Foo,那么您可以选择:
+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
Foo *newMe = [[self alloc] initWithTitle:title target:target action:action];
// Here you have access to all properties and methods of Foo unless newMe is nil.
return newMe;
}
Run Code Online (Sandbox Code Playgroud)
或者更一般而无法访问Foo的方法和属性:
+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
id newMe = [[self alloc] initWithTitle:title target:target action:action];
return newMe;
}
Run Code Online (Sandbox Code Playgroud)