我在一次培训中写了两个程序。但一项锻炼任务让我抓狂。不是任务本身,而是程序及其行为
第一个程序是计算一个人的BMI。在这里一切都很好。
main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
// Erstellt eine Instanz von Person
Person *person = [[Person alloc]init];
// Gibt den Instanzvariablen interessante Werte
[person setWeightInKilos:93.2];
[person setHeightInMeters:1.8];
// Ruft die Methode bodyMassIndex auf
float bmi = [person bodyMassIndex];
NSLog(@"person (%dKg, %.2fm) has a BMI of %.2f", [person weightInKilos],
[person heightInMeters], bmi);
}
return 0;
}
Person.h
@interface Person : NSObject
{
// Sie hat zwei Instanzvariablen
float heightInMeters;
int weightInKilos;
}
// Sie können diese Instanzvariablen anhand folgender Methoden setzen
@property float heightInMeters;
@property int weightInKilos;
// Diese Methode berechnet den Body-Mass-Index
- (float)bodyMassIndex;
@end
个人.m
#import "Person.h"
@implementation Person
@synthesize heightInMeters, weightInKilos;
- (float)bodyMassIndex
{
float h = [self heightInMeters];
return [self weightInKilos] / (h * h);
}
@end
这个程序是由培训的作者编写的。
我的任务是编写一个平等的程序。在我看来,它看起来完全一样:
main.m
#import <Foundation/Foundation.h>
#import "StocksHolding.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
StocksHolding *stock1 = [[StocksHolding alloc]init];
[stock1 purchaseSharePrice:1];
/*Here I geht the error "Instance method '-purchaseSharePrice:' not found (return type
defaults to 'id')*/
NSLog(@"%i", [stock1 purchaseSharePrice]);
}
return 0;
}
StockHoldings.h
#import <Foundation/Foundation.h>
@interface StocksHolding : NSObject
{
int purchaseSharePrice;
float currentSharePrice;
int numberOfShares;
}
@property int purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;
- (float)costInDollars;
- (float)valueInDollars;
@end
StockHoldings.m
#import "StocksHolding.h"
@implementation StocksHolding
@synthesize purchaseSharePrice, currentSharePrice, numberOfShares;
- (float)costInDollars
{
return purchaseSharePrice * numberOfShares;
}
- (float)valueInDollars
{
return currentSharePrice * numberOfShares;
}
@end
正如你所看到的。。。除了变量和方法的名称之外,几乎没有任何区别。错误在哪里?我在这个问题上坐了三个小时。
请帮我一把。
谢谢Christian
问题是您没有使用生成的setter方法。
purchaseSharePrice
是一个性质。
默认的setter是setPurchaseSharePrice:
,默认的getter是purchaseSharePrice
。
所以你可以做这个
[stock1 setPurchaseSharePrice:1];
或者这个
stock1.purchaseSharePrice = 1;
此外,当您想要使用生成的getter获取值时,您可以执行
int myPrice = [stock1 purchaseSharePrice];
或者这个
int myPrice = stock1.purchaseSharePrice;
正如您在设置和获取方面所看到的,拥有属性可以直接使用点语法和属性名称,而使用方法语法则需要使用由属性生成的方法名称。