<分区>
<分区>
我正在尝试开发一个 iOS 应用程序,允许用户输入一个单词,然后按按钮获取该单词的定义
实际上我有一个文件,其中包含单词及其定义,
Apple , the definition
orange , the definition
我写了代码,但不知道为什么它不起作用
#import "ViewController.h"
NSString *readLineAsNSString(FILE *file);
@interface ViewController ()
@end
@implementation ViewController
@synthesize text;
@synthesize lab;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)butt:(id)sender {
FILE *file = fopen("1.txt", "r");
NSString *a = text.text ;
bool found =FALSE;
while(!feof(file)|| !found )
{
NSString *line = readLineAsNSString(file);
if ((a= [[line componentsSeparatedByString:@","] objectAtIndex:1])) {
lab.text = [[line componentsSeparatedByString:@","] objectAtIndex:0];
}
fclose(file);
}
}
@end
谁能帮我找出问题所在吗?
最佳答案
恕我直言,实现此目的的一个简单方法是通过 plist。
这里有一个小例子来实现你想要的。
1) 创建您的 plist 文件。
在您的项目中,转到“添加新文件”。在左栏中,在 iOS 下(例如),选择“资源”。在主面板中选择“属性列表”文件。使用“Defs”之类的名称保存。
您的 plist 应如下所示。
2)读取plist文件(代码中的注释)
- (void)readDefinitionsFile
{
// grab the path where the plist is located, this plist ships with the main app bundle
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"Defs" ofType:@"plist"];
// create a dictionary starting from the plist you retrieved
NSDictionary* definitions = [NSDictionary dictionaryWithContentsOfFile:plistPath];
// JUST FOR TEST PURPOSES, read the keys and the values associated with that dictionary
for (NSString* key in [definitions allKeys]) {
NSLog(@"definition for key \"%@\" is \"%@\"", key, [definitions objectForKey:key]);
}
}
一些注释
上面是一个关于如何使用 plist 的简单示例。它没有提供实现您想要的功能的完整示例。在此基础上,您将能够实现您的目标。
您应该需要一个属性来引用您检索到的字典。例如,在您的 .m 中。
@interface ViewController ()
@property (nonatomic, strong) NSDictionary* definitions;
@end
@implementation ViewController
// other code here
// within readDefinitionsFile method
self.definitions = [NSDictionary dictionaryWithContentsOfFile:plistPath];
使用definitions
检索您感兴趣的定义。
NSString* definition = [self.definitions objectForKey:@"aKeyYouWillRetrieveFromSomewhere"];
if(definition) {
NSLog(@"definition is %@ for key %@", definition, @"aKeyYouWillRetrieveFromSomewhere");
} else {
NSLog(@"no definition for key %@", @"aKeyYouWillRetrieveFromSomewhere");
}
希望对您有所帮助。
关于ios - Objective-C 中如何从文件中读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15623959/
相关文章:
ios - 在iOS应用中实现可访问性(无Internet弹出窗口)的最简单方法是什么?
ios - UIImage 在旋转时向右移动 - 中心点错误?
java - 在 Android 中逐字读取文件的最佳方法是什么
ios - React Native - .xcworkspace 在从 git 中提取后不包含任何文件
ios - UITabbar 项目在升级到 Xcode 7 后单击后才会显示
ios - 当我在 iOS 上尝试 SQLite 时,INSERT 和 UPDATE 不起作用
iphone - 什么时候释放 NSThread 是安全的?
ios - 如何在 Objective c 中将整数数组转换为 NSString?