我正在制作一个货币转换器应用程序,但我在存储最新汇率方面遇到了一些问题。我有一个名为 applicationDidUpdateCurrency 的方法,可以使用按钮从应用程序内手动调用,或者在应用程序启动时通过单击"is"以发出警报。该方法获取最新的汇率并将它们添加到数组中。然后我让应用程序循环执行一系列语句,其中 NSArray 中的项目被移动到一个浮点值,然后记录到控制台。所有这些都很好。
+(void)applicationDidUpdateCurrency
{
NSError *error;
// Load .csv file.
NSString *allStates = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://download.finance.yahoo.com/d/quotes.csv?s=USDUSD=X,CNYUSD=X,GBPUSD=X,EGPUSD=X,CADUSD=X,EURUSD=X,&f=sl1d1t1ban&e=.csv"] encoding:NSUTF8StringEncoding error:&error];
// Remove all quotes from file, replace them with nothing.
NSString *strippedPartOne = [allStates stringByReplacingOccurrencesOfString:@"\"" withString:@""];
// Remove excess new lines from the csv file.
NSString *strippedPartTwo = [strippedPartOne stringByReplacingOccurrencesOfString:@"\r" withString:@""];
// Add strippedPartTwo to array.
NSArray *rows = [strippedPartTwo componentsSeparatedByString:@"\n"];
// NSArray *components;
for(int i=0; i<[rows count]; i++)
{
components = [[rows objectAtIndex:i] componentsSeparatedByString:@","];
// NSLog(@"Conversion: %@ Value: %@", [components objectAtIndex:0], [components objectAtIndex:1]);
if ([[rows objectAtIndex:i] isEqualToString:@""]) {
continue;
}
if (i==0) {
float floatUSD = 1;
NSLog(@"USD2: %f", floatUSD);
continue;
}
if (i==1) {
float beforeFloatCNY = [[components objectAtIndex:1] floatValue];
float floatCNY = 1 / beforeFloatCNY;
NSLog(@"CNY2: %f", floatCNY);
}
if (i==2) {
float beforeFloatGBP = [[components objectAtIndex:1] floatValue];
float floatGBP = 1 / beforeFloatGBP;
NSLog(@"GBP2: %f", floatGBP);
}
if (i==3) {
float beforeFloatEGP = [[components objectAtIndex:1] floatValue];
float floatEGP = 1 / beforeFloatEGP;
NSLog(@"EGP2: %f", floatEGP);
}
if (i==4) {
float beforeFloatCAD = [[components objectAtIndex:1] floatValue];
float floatCAD = 1 / beforeFloatCAD;
NSLog(@"CAD2: %f", floatCAD);
}
if (i==5) {
float beforeFloatEUR = [[components objectAtIndex:1] floatValue];
float floatEUR = 1 / beforeFloatEUR;
NSLog(@"EUR2: %f", floatEUR);
}
}
}
此方法位于与具有货币列表的 TableView Controller 相关联的同一文件中。我只是想将这些值放回该数组,以便可以更轻松地通过委托(delegate)将它们发送回主视图 Controller 。
在调用 applicationDidUpdateCurrency 方法后,我似乎无法使用简单的 NSLog(@"USD2: %f", floatUSD);再次显示该值。它在定义后立即正确记录,但即使在下一个 if 语句之后它也只显示为 0.000000。
我使用这段代码在 .h 文件中声明了 floatX 值。
@property (nonatomic, assign) float floatUSD;
谁能帮我解决这个问题?我只是想定义一个浮点值,将其放入一个数组中,然后在 TableView Controller 中选择该项目时将其发送回主视图 Controller 。
最佳答案
因为您要重新声明变量,而新声明的变量(现在在最内层的作用域中)隐藏了实例变量。 (如果你在打开警告的情况下编译它,你会得到一些关于这个的警告)。你不需要,事实上你不应该不重新声明这些。
此外,访问属性 本身,而不是支持实例变量。所以,总而言之,而不是
float floatUSD = 1;
写
self.floatUSD = 1;
关于iphone - 方法完成后, float 不保留其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788518/