对于重写的描述方法,“缺少方法声明的上下文”

时间:2012-04-26 21:04:39

标签: objective-c

我的重写描述方法得到了“方法声明的缺失上下文”。你能说出代码有什么问题吗?

#import <Foundation/Foundation.h>
#import "BNRItem.h"

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

  @autoreleasepool {

      // Create a mutable array object, store its address in items variable
    NSMutableArray *items = [[NSMutableArray alloc]init];

    BNRItem *p = [[BNRItem alloc]init];
    NSLog(@"%@ %@ %@ %d", [p itemName], [p dateCreated], [p serialNumber], [p valueInDollars]);

    // This creates a new NSString, "Red Sofa" and gives it to the BNRItem
    [p setItemName:@"Red Sofa"];

    // This creates a new NSString, "A1B2C" and gives it to the BNRItem
    [p setSerialNumber:@"A1B2C"];

    // We send the value 100 to be used as the valueInDollars of this BNRItem
    [p setValueInDollars:100];

    // Destroy the array pointed to by items
    items = nil;

  }
    return 0;
}

-(NSString *)description // Missing context for method declaration
{
  NSString *descriptionString =
  [[NSString alloc]initWithFormat:@"%@ (%@): Worth $%d, recorded on %@",
   itemName;
   serialNumber;
   valueInDollars;
   dateCreated];

return descriptionString;

}

BNRItem.m

#import "BNRItem.h"

@implementation BNRItem

-(void)setItemName:(NSString *)str {
  itemName = str;
}

-(NSString *)itemName {
  return itemName;
}

-(void)setSerialNumber:(NSString *)str {
  serialNumber = str;
}

-(NSString *)serialNumber {
  return serialNumber;
}

-(void)setValueInDollars:(int)i {
  valueInDollars = i;
}

-(int)valueInDollars {
  return valueInDollars;
}

-(NSDate *)dateCreated {
  return dateCreated;
}

-(NSString *)description
{
  NSString *descriptionString = 
  [[NSString alloc]initWithFormat:@"%@ (%@): Worth $%d, recorded on %@",
   itemName,
   serialNumber; // Expected "]"
   valueInDollars, // Expression result unused
   dateCreated]; //Extraneous "]" before ";"

  return descriptionString;
}


@end

2 个答案:

答案 0 :(得分:60)

您的方法似乎是main.m内的自由浮动。实例方法需要放在类的实现部分中。 (@implementation@end之间)。

我的猜测是你应该将该代码移到BNRItem.m。

答案 1 :(得分:2)

如果在Header oder .m文件的第一个开头有类似char的内容,也可能发生此错误。

^//
//  EMServices.m
//  MyController
//
//  Created by EMart on 09.01.14.
//  Copyright (c) 2014 EMart. All rights reserved.
//