今天开始学习《Objective-C 2.0程序设计》第七章,学习@property与@synthesize,编译时报错,代码如下:
文件Fraction.m
- #import "Fraction.h"
-
-
@synthesize numerator, denominator;
-
-
@implementation Fraction
-
-
-(void) print
-
{
-
NSLog(@"%i/%i", numerator, denominator);
-
}
-
-
-(double) convertToNum
-
{
-
if (denominator != 0)
-
return (double) numerator / denominator;
-
else
-
return 1.0;
-
}
-
-
@end
文件Fraction.h
- #import <Foundation/Foundation.h>
-
-
//the Fraction class
-
@interface Fraction : NSObject
-
{
-
int numerator;
-
int denominator;
-
}
-
-
@property int numerator, denominator;
-
-
-(void) print;
-
-(double) convertToNum;
-
-
@end
编译不过,报错:Missing context for property implementation declaration
查了google,得到如下信息:
- This can happen when you attempt to synthesize a property outside of the scope of your class' implementation.
-
-
Incorrect:
-
-
@synthesize yourProperty;
-
@implementation YourClass
-
@end
-
-
Correct:
-
-
@implementation YourClass
-
@synthesize yourProperty;
-
@end
原来是自己编写代码时将@synthesize方法放到了@implementation......@end之外!
于是修改代码如下:
- #import "Fraction.h"
-
-
@implementation Fraction
-
-
@synthesize numerator, denominator;
-
-
-(void) print
-
{
-
NSLog(@"%i/%i", numerator, denominator);
-
}
-
-
-(double) convertToNum
-
{
-
if (denominator != 0)
-
return (double) numerator / denominator;
-
else
-
return 1.0;
-
}
-
-
@end
编译顺利通过!看来习惯很重要,一定注意@synthesize方法放到@implementation......@end之内~
本文仅作警示!
阅读(4962) | 评论(0) | 转发(0) |