我一直在编写一个简单的应用程序,从 .csv 文件中绘制初始值,然后添加到它们,然后尝试将修改后的数据写回同一个 CSV 文件。终端窗口中的输出表明它工作正常,但是当我查看文件或从另一个引导访问它时(我正在 Xcode 的 iPhone 模拟器上测试它),它似乎不起作用。有人可以告诉我哪里出错了吗?这是我的代码:
-(IBAction)AddButtonPressed:(id)sender{
// Get the input from the input field and add it to the sum in the bank field
float a = ([input.text floatValue]);
float b = a+([earned.text floatValue]);
// adding the old value of 'earned' text field to the value from the input field and update the interface
earned.text = [[NSString alloc] initWithFormat:@"%4.2f",b];
// THIS IS THE BEGINNINGS OF THE CODE FOR WRITING OUT TO A .CSV FILE SO THAT DATA CAN BE USED LATER IN EXCEL
NSString *path = [[NSBundle mainBundle] pathForResource:@"Income" ofType:@"csv"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSLog(@"found it");
NSString *contents = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"string looks like this\: %@", contents);
//set the contents of income to be the same as what's currently in income.csv
[income setString:contents];
NSLog(@"income contains\: %@", income);
//NEXT Apend income to add NSDATE, Textinput and the float value 'a'
//Get the Date...
NSDateComponents *components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
//... And apend it into a readable string with a comma on the end
NSString *theDate = [[NSString alloc] init];
theDate = [NSString stringWithFormat:@"%d.%d.%d", day,month,year];
NSLog(@"The Date is %@", theDate);
//holder string till I get the text input wired up in the interface
NSString *text = [[NSString alloc]init];
text = @"filler words";
//turn the float entered in the GUI to a string ready for adding to the 'income' mutable array
NSString *amountAdded = [[NSString alloc]init];
amountAdded = [NSString stringWithFormat:@"%4.2f", a];
//format the final string and pass it to our 'income' NSMutable Array
NSString *finalString = [[NSString alloc] init];
finalString = [NSString stringWithFormat:@"\n %@, %@, %@", theDate, text, amountAdded];
NSLog(@"final string is %@", finalString);
[income appendString:finalString];
NSLog(@"income now reads %@", income);
[income writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSLog(@"completed writing to income.csv which now reads %@", contents);
}
else{
NSLog(@"not a sausage");
}