首页 > 其他 > 详细

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

时间:2018-09-27 17:43:00      阅读:187      评论:0      收藏:0      [点我收藏+]
#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方法必须是实例方法,并且必须返回实例对象,这样要求的原因同上。

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

原文:https://www.cnblogs.com/lxlx1798/p/9714286.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!