我正在通过Stephen G Kochan的“Objective C中的编程”学习ObjectiveC,我在一个例子中遇到了一些困难。它创建了一个继承自Object的简单Fraction类。这就是我遇到麻烦的地方,当我尝试发送被Object而不是Fraction理解的消息时,例如init,alloc或free(参见下面的代码):
// Fraction
#import <stdio.h>
#import <objc/Object.h> // base object
// @interface section
@interface Fraction: Object
{
int numerator;
int denominator;
}
- (void) print;
- (void) setNumerator: (int) n;
- (void) setDenominator: (int) d;
@end
// @implementation section
@implementation Fraction;
-(void) print
{
printf(" %i/%i ", numerator, denominator);
}
-(void) setNumerator: (int) n
{
numerator = n;
}
-(void) setDenominator: (int) d
{
denominator = d;
}
@end
// Program section
int main( int argc, char *argv[])
{
Fraction *myFraction;
// Create Instance of fraction
myFraction = [Fraction alloc];
myFraction = [Fraction init];
// Set fraction to 1/3
[myFraction setNumerator: 1];
[myFraction setDenominator: 3];
// Display the fraction
printf("The value of my fraction is: ");
[myFraction print];
printf("\n");
// Destroy the instance
[myFraction free];
return 0;
}
编译时:
gcc fraction.m -o fraction -l objc
我收到以下警告:
fraction.m: In function ‘main’:
fraction.m:47: warning: ‘Fraction’ may not respond to ‘+alloc’
fraction.m:47: warning: (Messages without a matching method signature
fraction.m:47: warning: will be assumed to return ‘id’ and accept
fraction.m:47: warning: ‘...’ as arguments.)
fraction.m:48: warning: ‘Fraction’ may not respond to ‘+init’
fraction.m:62: warning: ‘Fraction’ may not respond to ‘-free’
fernando@McFofo ~/code/learning objective c:: ./fraction
objc[1678]: Fraction: Does not recognize selector forward::
该程序在运行时抱怨非法指令......
有人知道发生了什么事吗?
答案 0 :(得分:1)
Cocoa中的类(最流行的Objective-C库,它们几乎是同义词)倾向于继承自Cocoa根类NSObject
。记录here。
还有NSObject
protocol,由NSProxy
实施。它构成了Cocoa对Distributed Objects的支持的基础。也就是说,我们可能已经超越了自己!
我还注意到您正在尝试执行以下操作:
Fraction *myFraction;
myFraction = [Fraction alloc];
myFraction = [Fraction init];
您正在为对象分配内存,然后通过用另一个覆盖指针来丢失它。标准做法是在一行上进行如下操作:
Fraction *myFraction = [[Fraction alloc] init];
如果必须多行一行,则必须执行以下操作:
Fraction *myFraction;
myFraction = [Fraction alloc];
myFraction = [myFraction init];
// myFraction is now ready to go!
我偶然发现site指的是您正在阅读的书。网站上突出显示的示例继承自NSObject
和导入<Foundation/NSObject.h>
。你有没有特别的理由避开这个并决定运行时提供的Object
类?