草庐IT

ios - 从字典和数组的 plist 中读取/写入数据,并将不同级别加载到 TableView

coder 2024-01-19 原文

我对使用属性列表有点困惑。我已经阅读了关于这个主题的大部分其他问题,但我仍然很困惑,因为它们只进入一层,所以任何帮助将不胜感激。

我想像这样加载一个存储数据的 plist:

我的 Storyboard 中有三个 ViewController(两个 TableViewController 和一个空白),我想显示不同级别的信息:

  1. 人员类别( friend 等)
  2. 这些类别中的人员姓名(Bob 等)
  3. 关于人物的信息(最喜欢的颜色等)

如何将文件读/写到 plist,以及如何跨多个 View 访问该信息?

读取数据后,如何在不同的 TableViewController 中显示信息?

最佳答案

假设您有一个这样的 plist 文件:

和这段代码:

@implementation ViewController


NSDictionary *dictionary;

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    NSMutableArray *array=[[NSMutableArray alloc]init];
    array=[NSMutableArray arrayWithContentsOfFile:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"root.plist"]];

    dictionary = [array objectAtIndex:0];


}

- (NSString *)applicationDocumentsDirectory {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSLog(@"numberOfSectionsInTableView:%lu",(unsigned long)dictionary.count);
    return dictionary.count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [[[dictionary allKeys] objectAtIndex:section] capitalizedString];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    NSArray *peopleArray = [dictionary objectForKey:[[dictionary allKeys] objectAtIndex:indexPath.section]];

    cell.textLabel.text = [[peopleArray objectAtIndex:indexPath.row]objectForKey:@"name"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"Color:%@ - Gender:%@",[[peopleArray objectAtIndex:indexPath.row]objectForKey:@"favorite color"],[[peopleArray objectAtIndex:indexPath.row]objectForKey:@"gender"]];

    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key =[[dictionary allKeys] objectAtIndex:section];
    NSLog(@"numberOfRowsInSection:%lu",(unsigned long)[[dictionary objectForKey:key] count]);
    return [[dictionary objectForKey:key] count];
}

它会给你这个输出:

(假设你有一个带有 Delegate 和 DataSource 的 tableView)

我知道您要求在不同的 TableView 中显示“Friends”和“Enemies”,但我在同一个 tableView 的不同部分中同时使用了这两者。但我的代码可以帮助您入门。

如果您需要有关 UITableView 的额外帮助,请参阅 Apple UITableView Class Reference

如果有必要,我使用此代码在我的测试项目中生成示例 plist 文件:

NSMutableArray *root=[[NSMutableArray alloc]init];
NSMutableArray *friendsarray = [[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:@"Jill" forKey:@"name"];
[dict setObject:@"green" forKey:@"favorite color"];
[dict setObject:@"female" forKey:@"gender"];

[friendsarray addObject:dict];

NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
[dict2 setObject:@"Bob" forKey:@"name"];
[dict2 setObject:@"Blue" forKey:@"favorite color"];
[dict2 setObject:@"male" forKey:@"gender"];

[friendsarray addObject:dict2];

NSMutableArray *enemiesarray = [[NSMutableArray alloc]init];


NSMutableDictionary *dict3 = [[NSMutableDictionary alloc]init];
[dict3 setObject:@"Michael" forKey:@"name"];
[dict3 setObject:@"Red" forKey:@"favorite color"];
[dict3 setObject:@"male" forKey:@"gender"];

[enemiesarray addObject:dict3];

NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
[d setObject:friendsarray forKey:@"friends"];
[d setObject:enemiesarray forKey:@"enemies"];


[root addObject:d];

[root writeToFile:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"root.plist"] atomically:YES];

关于ios - 从字典和数组的 plist 中读取/写入数据,并将不同级别加载到 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21978626/

有关ios - 从字典和数组的 plist 中读取/写入数据,并将不同级别加载到 TableView的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  3. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  4. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  7. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  8. python - 如何读取 MIDI 文件、更改其乐器并将其写回? - 2

    我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的

  9. ruby-on-rails - 从应用程序中自定义文件夹内的命名空间自动加载 - 2

    我们目前正在为ROR3.2开发自定义cms引擎。在这个过程中,我们希望成为我们的rails应用程序中的一等公民的几个类类型起源,这意味着它们应该驻留在应用程序的app文件夹下,它是插件。目前我们有以下类型:数据源数据类型查看我在app文件夹下创建了多个目录来保存这些:应用/数据源应用/数据类型应用/View更多类型将随之而来,我有点担心应用程序文件夹被这么多目录污染。因此,我想将它们移动到一个子目录/模块中,该子目录/模块包含cms定义的所有类型。所有类都应位于MyCms命名空间内,目录布局应如下所示:应用程序/my_cms/data_source应用程序/my_cms/data_ty

  10. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

随机推荐