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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#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 开头,导致错误:

1
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   梁飞宇  阅读(319)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示