首先,我对Objective c不太满意,我正在尝试将C ++类转换为Objective C,而我在我的课上实现时遇到了麻烦这就是我得到的c ++
UniqueWord::UniqueWord(const string word, const int line)
{
wordCatalog=word;
count = 0;
addLine(line);
}
//Deconstructor.
UniqueWord::~UniqueWord(void)
{
}
这就是我为Objective C获得的东西
@implementation UniqueWord
-(id)initWithString:(NSString*)str andline:(NSInteger)line{
_wordCatalog=str;
count=0;
addline(line);
return ?//return what? it states (Control reaches end of non-void function)
}
我对目标c中的课程很陌生,所以我也要求一个愚蠢的答案,世界上有什么是“id”,你如何使用它?
答案 0 :(得分:2)
Objective C构造函数有点不同。您应该创建以下内容:
-(instancetype)initWithString:(NSString*)str andline:(NSInteger)line{
self = [super init];
if(self == nil) return nil;
_wordCatalog=str;
count=0;
addline(line);
return self;
}
答案 1 :(得分:2)
id
是Objective-C中的泛型类。这有点类似于C ++的void*
,但是从执行环境获得了更多的支持,因此不需要太多的类型转换。
C ++中没有并行概念:无类型对象引用允许您动态使用对象,并在运行时检查调用的细节,而不是在编译时检查。
另请注意,Objective-C使用初始化程序而不是构造函数。这两个用途类似,但不相同:构造函数可以与运算符new
一起运行,也可以与运算符分开运行,而初始化程序只能使用分配方法运行。此外,初始值设定项可以返回不同的对象来代替alloc
提供的对象;建设者不能那样做。
答案 2 :(得分:1)
id
是Objective-C中任何对象的一个点。 init方法返回已分配和实例化的对象。我会在https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Initialization/Initialization.html
在使用上面所说的文章时,你会想写一些类似的东西。
- (instancetype)initWithString:(NSString *)str andLine:(NSInteger)line {
self = [super init];
if (self) {
_wordCatalog = str;
}
return self;
答案 3 :(得分:0)
init方法的典型形式(您应该使用)如下所示:
- (id)init
{
if ( (self = [super init] ) )
{
[other code you want in the constructor]
}
return self;
}
因此,对于您拥有的方法,它看起来应该是这样的:
-(id)initWithString:(NSString*)str andline:(NSInteger)line{
if ( (self = [super init]) )
{
_wordCatalog=str;
count=0;
addline(line);
}
return self;
}
也就是说,除非超类有一个initWithString:andline:构造函数,在这种情况下你会使用
if ( (self = [super initWithString:string andline:line) )
作为if语句。