![](/img/trans.png)
[英]incompatible pointer types assigning to 'UILabel *__weak' to 'NSString *__strong'?
[英]Obj-C: Incompatible pointer types assigning to 'UITextfield *_strong' from 'NSNumber *_strong
好的,我已經看過其他類似的問題,但是我無法弄清楚為什么NSNumber與UIText字段不兼容。
我的.h
@property (weak, nonatomic) IBOutlet UITextField *initialBudget;
@property (weak, nonatomic) IBOutlet UITextField *expenses;
@property (weak, nonatomic) IBOutlet UITextField *timeSpent;
@property (weak, nonatomic) IBOutlet UITextField *incomePerHour;
這些是我的計算
- (IBAction)calculateResults:(id)sender {
double budget = [initialBudget.text doubleValue ];
double expense = [expenses.text doubleValue];
double time = [timeSpent.text doubleValue];
double hourlyIncome = (budget - expense)/time;
NSNumber *resultNumber = [[NSNumber alloc] initWithDouble:hourlyIncome];
incomePerHour = resultNumber;
}
任何幫助都會很好,謝謝
您想要設置UITextField的text屬性。
[incomePerHour setText:[resultNumber stringValue]];
再見!
編輯:您也可以在沒有NSNumber的情況下執行此操作:
[incomePerHour setText:[NSString stringWithFormat:@"%f", hourlyIncome]];
由於%f的緣故,精度會降低(默認情況下四舍五入為十進制的6位),但如果要使用42位小數,則可以使用%.42f
。
我無法弄清楚為什么NSNumber與UIText字段不兼容。
因為它們是不同類型的對象,並且像C ++和其他語言一樣,Objective-C中沒有隱式類型轉換(除了免費的橋接)。 實際上,將數字對象隱式轉換為文本字段對象並沒有多大意義。
您要做的是:
// Set incomePerHour text field text property with number formatted to two decimal places
incomePerHour.text = [NSString stringWithFormat:@"%.2f", hourlyIncome];
PS要創建一個NSNumber
,您可以執行以下操作:
NSNumber *resultNumber = @(hourlyIncome);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.