你如何正确地组成@interface部分?

时间:2013-07-26 23:09:29

标签: objective-c

我是Objective-C的新手并创建了这个基本程序。它在@interface部分给出了错误,是否有任何简单的解释可以让初学者了解如何构建@interface@implementation部分?下面的程序出了什么问题?

    #import <Foundation/Foundation.h>

    @interface Rectangle : NSObject {
    //declare methods
    - (void) setWidth: (int) a;
    - (void) setHieght: (int) b;
    - (double) perimeter;
    - (double) area;

    }
    @end

     @implementation Rectangle


    {
    double area;
    double perimeter;
    int width;
    int height;
    }
    - (void) setWidth: (int) a
    {
        width = a;  
    }
    - (void) setHieght: (int) b
   {
    hieght = b;
    }

    @end

    int main (int argc, const char * argv[])
    {

    NSAutoreleasePool * Rectangle = [[NSAutoreleasePool alloc] init];
    int a = 4
    int b = 5
    int area = a * b;
    int perimeter = 2 * (a +b);

    NSLog(@"With width of %i and Hieght of %i", a, b);
    NSLog(@"The perimeter is %i", perimeter);
    NSLog(@"The Area is %i", area);

    [pool drain];
    return 0;
    }

2 个答案:

答案 0 :(得分:3)

您列出了ivars应该去的方法。它应该是:

@interface Rectangle : NSObject {

    //instance variables here
}

// declare methods or properties here
- (void) setWidth: (int) a;
- (void) setHieght: (int) b;
- (double) perimeter;
- (double) area;

@end

正如已经指出的那样,你可以简单地删除大括号。

答案 1 :(得分:0)

您的代码中存在一些问题,我们稍后会看到它们,但作为初学者,您需要了解一些事情:

  • main()适用于您项目中的main.m课程,请不要在此处搞乱,请使用init()代替
  • 您未在@implementaion
  • 的{}范围内声明方法
  • @end @implementation @implementation后,不应写任何要执行的内容
  • @end不应限制在{}范围,因为它以#import <Foundation/Foundation.h> @interface Rectangle : NSObject //declare methods - (void) setWidth: (int) a; - (void) setHieght: (int) b; - (double) perimeter; - (double) area; @end @implementation Rectangle
  • 结尾
  • 还有一些,请在http://www.slideshare.net/musial-bright/objective-c-for-beginners
  • 找到它

所以你应该这样:

- (void) setWidth: (int) a {
    width = a;
}

- (void) setHieght: (int) b {
    height = b;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        int a = 4;
        int b = 5;
        int area = a * b;
        int perimeter = 2 * (a +b);

        NSLog(@"With width of %i and Hieght of %i", a, b);
        NSLog(@"The perimeter is %i", perimeter);
        NSLog(@"The Area is %i", area);
    }
    return self;
}

@end

{         双面积;         双周长;         int宽度;         int height; }

{{1}}