【问题标题】:Objective C - Method Definition not in @implementation context目标 C - 方法定义不在 @implementation 上下文中
【发布时间】:2017-11-30 12:07:56
【问题描述】:

我的代码:

#import <Foundation/Foundation.h>

-(NSString *) Fibonacci:(int) number{
//Fibonacci Calculations
}

int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Fibonacci Output: %@", Fibonacci(5));
[pool drain];
return 0;
}

我对 Objective-C 世界很陌生,因此无法完成上述工作。 面临以下错误:

错误: source_file.m:5:1:错误:方法定义不在@implementation 上下文中 -(NSString *) lastdigitsFibonacci:(int) number{ ^ source_file.m:6: 被早期的错误弄糊涂了,退出

我们将非常感谢您对上述内容的任何帮助。谢谢

【问题讨论】:

  • @Who-So-Ever-Downvoted-The-Question:关心解释是什么让你这样做的?
  • Fibonacci(5) 似乎是一个函数。 -(NSString *) Fibonacci:(int) number 好像是一种方法。

标签: objective-c objective-c++ objective-c-runtime


【解决方案1】:

正如@Larme 所说,Fibonacci(5) 似乎是一个函数。 -(NSString *) Fibonacci:(int) number 好像是一种方法。

所以要调用Fibonacci(5),你应该将-(NSString *) Fibonacci:(int) number重写为一个函数。

NSString* Fibonacci(int number) {

  int t1 = 0;
  int t2 = number > 1 ? 1 : 0;
  int tmp;

  for (int i = 3; i <= number; i++) {
    tmp = t2;
    t2 += t1;
    t1 = tmp;
  }

  return [NSString stringWithFormat:@"%lu", t2];
}

int main(int argc, char* argv[]) {
  @autoreleasepool {
    NSLog(@"%@", Fibonacci(999));
  }
}

【讨论】:

  • 非常感谢您的回答。 :)
  • & @Sangram S. 你能帮我打印出斐波那契数列中 n=999 的输出吗? NSUInteger t1=0, t2=1,i=0,nextTerm; //NSLog(@"%i", number); for (i = 1; i %lu",t1);
  • @genius_monkey 更新了我的答案。祝你好运;)
  • 不要调用 UI applicationmain()
  • @bbum 谢谢先生!
【解决方案2】:
#import <Foundation/Foundation.h>

NSString*  Fibonacci(int number) ;

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Fibonacci Output: %@", Fibonacci(5));

    }
    return 0;
}

NSString*  Fibonacci(int number)
{
    //Fibonacci Calculations and return
}

【讨论】:

  • 非常感谢您指出差异。欣赏它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多