Xcode工程编译错误:“Cannot assign to 'self' outside of a method in the init family”

#import <Foundation/Foundation.h>
 
@interface EOCRectangle : NSObject<NSCoding>
@property (nonatomic , readonly , assign) float width;
@property (nonatomic , readonly , assign) float height;
-(id)initWithWidth:(float) width andHeight:(float) height;
@end
 
#import "EOCRectangle.h"
/**
 *  为对象提供必要信息以便其能完成工作的初始化方法叫做“全能初始化方法”
 */
@implementation EOCRectangle
-(id)initWithWidth:(float) width andHeight:(float) height
{
    if ((self = [super init])){
        _width = width;
        _height = height;
    }
    return self;
}
/**
 *  初始化设置默认的值
 */
//-(id)init
//{
//    return [self initWithWidth:10.0 andHeight:10.0];
//}
/**
 *  初始化抛出异常
 */
-(id)init{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                   reason:@"Must use initWithWidth:(float) width andHeight:(float) height instead"
                                 userInfo:nil];
 
}
/**
 *  初始化NSCoding
 */
-(id)initWithCoder:(NSCoder *)aDecoder{
    if ((self = [super init])){
        _width = [aDecoder decodeFloatForKey:@"width"];
        _height = [aDecoder decodeFloatForKey:@"height"];
    }
    return self;
}
@end

 但在我自己写的过程中,忘记将初始化方法名以 init 开头,导致错误:

 Cannot assign to 'self' outside of a method in the init family

 

原因:在ARC有效时,只能在init方法中给self赋值,Xcode判断是否为init方法规则:方法返回id,并且名字以init+大写字母开头+其他  为准则。

如果此时关闭ARC,会发现刚才的错误提示不见了:





如果将初始化方法名改为 - initialize,同样有错误提示,因为不符合上面的命名规则。

这样的命名规则是为了保证ARC开启时内存管理不出错,同时,init方法必须是实例方法,并且必须返回实例对象,这样要求的原因同上。

posted on 2018-09-27 17:12  梁飞宇  阅读(313)  评论(0编辑  收藏  举报