Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1331687
  • 博文数量: 206
  • 博客积分: 10571
  • 博客等级: 上将
  • 技术积分: 2610
  • 用 户 组: 普通用户
  • 注册时间: 2007-04-30 11:50
文章分类
文章存档

2014年(1)

2013年(4)

2012年(18)

2010年(14)

2009年(31)

2008年(3)

2007年(135)

分类: 系统运维

2012-02-16 17:10:52

今天开始学习《Objective-C 2.0程序设计》第七章,学习@property与@synthesize,编译时报错,代码如下:

文件Fraction.m
  1. #import "Fraction.h"

  2. @synthesize numerator, denominator;

  3. @implementation Fraction

  4. -(void) print
  5. {
  6.     NSLog(@"%i/%i", numerator, denominator);
  7. }

  8. -(double) convertToNum
  9. {
  10.     if (denominator != 0)
  11.         return (double) numerator / denominator;
  12.     else
  13.         return 1.0;
  14. }

  15. @end
文件Fraction.h
  1. #import <Foundation/Foundation.h>

  2. //the Fraction class
  3. @interface Fraction : NSObject
  4. {
  5.     int numerator;
  6.     int denominator;
  7. }

  8. @property int numerator, denominator;

  9. -(void) print;
  10. -(double) convertToNum;

  11. @end
编译不过,报错:Missing context for property implementation declaration

查了google,得到如下信息:
  1. This can happen when you attempt to synthesize a property outside of the scope of your class' implementation.

  2. Incorrect:

  3. @synthesize yourProperty;
  4. @implementation YourClass
  5. @end

  6. Correct:

  7. @implementation YourClass
  8. @synthesize yourProperty;
  9. @end
原来是自己编写代码时将@synthesize方法放到了@implementation......@end之外!
于是修改代码如下:
  1. #import "Fraction.h"

  2. @implementation Fraction

  3. @synthesize numerator, denominator;

  4. -(void) print
  5. {
  6.     NSLog(@"%i/%i", numerator, denominator);
  7. }

  8. -(double) convertToNum
  9. {
  10.     if (denominator != 0)
  11.         return (double) numerator / denominator;
  12.     else
  13.         return 1.0;
  14. }

  15. @end
编译顺利通过!看来习惯很重要,一定注意@synthesize方法放到@implementation......@end之内~

本文仅作警示!





阅读(4933) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~