我刚刚开始学习objective-C。我的第一个问题是我无法运行下面的源代码。
这是我的源代码:
#import <Foundation/NSObject.h>
#import <stdio.h>
@interface Volume : NSObject
-(id)init;
@end
@implementation Volume
-(id)init
{
self = [super init];
return self;
}
@end
int main(void){
id o;
o = [Volume init];
}
这是我的错误输出:
$cc 96.m -framework Foundation
$./a.out
2014-09-18 10:10:40.116 a.out[759:507] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[Volume<0x1069ca0f8> init]: cannot init a class object.'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff9019525c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff951f4e75 objc_exception_throw + 43
2 CoreFoundation 0x00007fff90198490 +[NSObject(NSObject) dealloc] + 0
3 a.out 0x00000001069c9f46 main + 38
4 libdyld.dylib 0x00007fff93bab5fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Abort trap: 6
这是我的环境:
$cc --version
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix
谢谢。
最佳答案
使用alloc/init
[Volume init]
是无效消息。 init
没有类方法。
但是,[Volume alloc]
创建一个 Volume 对象,然后您可以对其调用 init
。
[[Volume alloc] init]
有效,因为一旦对象被分配,就可以对其进行初始化。
alloc
在内存中保留对象存在的位置。 init
实际上会占用该内存并设置一个您可以使用的对象。
使用new
如果您希望能够调用单个方法而不是[[Volume alloc] init]
,则可以调用[Volume new]
。虽然这是有效的,但并不经常使用。
使用类对象初始化器
您还可以实现类方法来创建新卷。
+ (instancetype) volume{
return [[Volume alloc]init];
}
然后,您可以使用Volume *vol = [Volume 音量];
关于objective-c - 为什么当我执行 Objective-C 程序时会出现错误 "cannot init a class object"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25902781/