0

First of all, I'm a beginner in objective-C. At the moment I'm trying to resolve the following problem:

@interface Animal : NSObject {
  @private
  NSString* m_name;
}
-(Animal*) initName:(NSString*)name;
-(void) printName;

@implementation Animal
-(Animal*) initName:(NSString*)name {
  self = [super init];
  m_name = name;
  return self;
}
-(void) printName {
  NSLog(@"%s", m_name);
}
@end

@interface Bird : Animal {
}
-(Bird*) initName:(NSString*)name;

@implementation Bird
-(Bird*) initName:(NSString*)name {
  self = [super initName:name];
  return self;
}
@end

int main() {
  Animal* bird = [[Bird alloc] initName:@"abird"];  // warning: assignment from distinct Objective-C type
  [bird printName];  // prints invalid letters
  [bird release];
}

I want to propagate the constructor argument name to the superclass, but it doesn't work. I also tried to print the name inside the constructor without any success.

All necessary headers are included. The warning warning: assignment from distinct Objective-C type [enabled by default] when creating the child class object is the only warning I get.

Does anyone has an idea how I could solve this problem?

Greetings Dan

4

1 回答 1

4

m_name是一个NSString,不是一个char *。您必须使用%@格式说明符而不是%s. 阅读格式字符串的文档。

注释:

  • Objective-C 不是 C++。不要试图强制执行 C++ 风格的命名约定。调用那个实例变量name, or animalName, theNameor 什么的。不要叫它m_name

  • 初始化程序通常称为initWithWhatever:,而不是initWhatever:。它更好地反映了方法的目的(您使用名称初始化对象,而不是名称本身)。

  • 请检查 [super init]. 如果它返回nil,您的初始化程序将崩溃。一个惯用的解决方案是if (self = [super initWithName:name])

  • 初始化方法同样按照惯例返回id

于 2013-06-25T09:05:33.880 回答