NSScanner 不导入数据
我正在尝试将 csv 文件中的一组默认数据加载到我的核心数据数据库中。因此,最初我尝试读取 csv 文件并将其输出到日志,然后再尝试将其添加到核心数据数据库。
这是我正在使用的代码;
//Find import file;
NSString *defaultCSVPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"csv"];
//Get the data into a string
NSString *fileString = [NSString stringWithContentsOfFile:defaultCSVPath encoding:NSUTF8StringEncoding error:nil];
if ( nil == fileString ) {
NSLog(@"Could not open file data.csv");
abort();
}
// Create the scanner
NSScanner *scanner = [NSScanner scannerWithString:fileString];
// Ignore new lines
[scanner setCharactersToBeSkipped:
[NSCharacterSet characterSetWithCharactersInString:@"\n"]];
NSString *sNumber = @"";
NSString *sTitle = @"";
//Gets to here and this expression is never TRUE
while ( [scanner scanString:@"," intoString:&sNumber] && [scanner scanString:@"," intoString:&sTitle]) {
NSLog(@"sNumber:%@ sTitle:%@",sNumber,sTitle);
}
我正在使用的示例数据是;
A15Q,Test1
F74443AAZ,Test2
当我跟踪代码时,我到达 while 子句,它只是跳过它。
I'm trying to load a default set of data from a csv file into my core data db. So initially i'm trying to read in a csv file and output it to the log before trying to add it to the core data database.
This is the code i'm using;
//Find import file;
NSString *defaultCSVPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"csv"];
//Get the data into a string
NSString *fileString = [NSString stringWithContentsOfFile:defaultCSVPath encoding:NSUTF8StringEncoding error:nil];
if ( nil == fileString ) {
NSLog(@"Could not open file data.csv");
abort();
}
// Create the scanner
NSScanner *scanner = [NSScanner scannerWithString:fileString];
// Ignore new lines
[scanner setCharactersToBeSkipped:
[NSCharacterSet characterSetWithCharactersInString:@"\n"]];
NSString *sNumber = @"";
NSString *sTitle = @"";
//Gets to here and this expression is never TRUE
while ( [scanner scanString:@"," intoString:&sNumber] && [scanner scanString:@"," intoString:&sTitle]) {
NSLog(@"sNumber:%@ sTitle:%@",sNumber,sTitle);
}
The sample data i'm using is;
A15Q,Test1
F74443AAZ,Test2
When I trace the code, I get to the while clause and it just skips over it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不知道为什么将 sNumber 和 sTitle 初始化为@""; nil 是更好的默认值(或者你可以不初始化它们)。
[scanner scanString:@"," intoString:&foo]
期望看到逗号并返回foo
中的逗号(这样做是为了保持一致性,并且(我认为) Unicode wotsits)。您可能想做类似这样的事情:
(出于某种原因,我需要在此处粘贴一些内容以使格式正常工作。)
假设您正在尝试解析 CSV,这有其自身的问题:
"a,b","c,d,e,f"
)。Not sure why you initialize sNumber and sTitle to @""; nil is a better default (or you can just not initialize them).
[scanner scanString:@"," intoString:&foo]
expects to see a comma and returns the comma infoo
(it does this for consistency and (I think) Unicode wotsits).You probably want to do something more like this:
(And I need to stick something here for the formatting to work, for some reason.)
Assuming you're trying to parse CSV, this has its own problems:
"a,b","c,d,e,f"
).