Multiple Arrays From Plist

余生颓废 提交于 2019-12-05 07:14:44

问题


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
  <array>
    <string>Title 1</string>
    <string>Subtitle 1</string>
    <string>image1.png</string>
  </array>
  <array>
    <string>Title 2</string>
    <string>Subtitle 2</string>
    <string>image2.png</string>
  </array>
</array>
</plist>

This is my Plist file for an app I am working on.

I am not sure on how to take the first string of many arrays to create an NSMutableArray with all the titles and again for the subtitles and image names.

My workaround at the moment is creating 3 separate Plist files for each type of string which can be a nuisance.


回答1:


To answer your question while retaining the plist data structure, you could simply do something like the following:

NSArray *rootArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"your-plist" ofType:@"plist"]];
int numItems = [rootArray count];
NSMutableArray *titles = [NSMutableArray arrayWithCapacity:numItems];
NSMutableArray *subtitles = [NSMutableArray arrayWithCapacity:numItems];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:numItems];

for (NSArray *itemData in rootArray) {
    [titles addObject:[itemData objectAtIndex:0]];
    [subtitles addObject:[itemData objectAtIndex:1]];
    [images addObject:[itemData objectAtIndex:2]];
}

However, I would advise you to use a structure like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
  <dict>
    <key>title</key>
    <string>Title 1</string>
    <key>subtitle</key>
    <string>Subtitle 1</string>
    <key>image</key>
    <string>image1.png</string>
  </dict>
  <dict>
    <key>title</key>
    <string>Title 2</string>
    <key>subtitle</key>
    <string>Subtitle 2</string>
    <key>image</key>
    <string>image2.png</string>
  </dict>
</array>
</plist>

At which point you could use the more explicit code as follows:

NSArray *rootArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"your-plist" ofType:@"plist"]];
int numItems = [rootArray count];
NSMutableArray *titles = [NSMutableArray arrayWithCapacity:numItems];
NSMutableArray *subtitles = [NSMutableArray arrayWithCapacity:numItems];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:numItems];

for (NSDictionary *itemData in rootArray) {
    [titles addObject:[itemData objectForKey:@"title"]];
    [subtitles addObject:[itemData objectForKey:@"subtitle"]];
    [images addObject:[itemData objectForKey:@"image"]];
}


来源:https://stackoverflow.com/questions/6192451/multiple-arrays-from-plist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!