I'm using a piece of code I've used before with success to load a plist into an array:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
The initWithContentsOf File is failing (array is null, suggesting it can't find the plist in the app bundle).
Under the iPhone simulator I've checked that the path created by the first line points to the app file (it does)开发者_如何转开发, and used the Finder context menu "Show package contants" to prove to myself that "species_name.plist" is actually in the bundle--with a length that suggests it contains stuff, so it should work (and has in other iOS apps I've written). Suggestions most welcome...
[env Xcode 4.2 beta, iOS 4.3.2].
You should use initWithContentsOfFile:
method of NSDictionary
instance, not NSArray
.
Here is sample:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
NSArray *array = [NSArray arrayWithArray:[dict objectForKey:@"Root"]];
Or this:
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *path = [[NSBundle mainBundle] pathForResource:@"startups" ofType:@"plist"];
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:path];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
NSArray *array = [NSArray arrayWithArray:[temp objectForKey:@"Root"]];
EDIT
You can use initWithContentsOfFile:
method of NSArray
with file created with writeToFile:atomically:
method of NSArray
. Plist created with writeToFile:atomically:
has this stucture:
<plist version="1.0">
<array>
...Content...
</array>
</plist>
And Plist created in XCode has this stucture:
<plist version="1.0">
<dict>
...Content...
</dict>
</plist>
Thats why initWithContentsOfFile:
method of NSArray
dosnt work.
plist
of this type:
OR (basically both are same)
Can be read like this:
NSString *file = [[NSBundle mainBundle] pathForResource:@"appFeatures" ofType:@"plist"];
NSArray *_arrFeats = [NSArray arrayWithContentsOfFile:file];
NSLog(@"%d", _arrFeats.count);
Where appFeatures
is name of the plist
.
(iOS 6.1)
Try this simple metod:
- (void)viewDidLoad
{
[super viewDidLoad];
[self plistData];
}
- (void)plistData
{
NSString *file = [[NSBundle mainBundle] pathForResource:@"appFeatures" ofType:@"plist"];
NSArray *messages = [NSArray arrayWithContentsOfFile:file];
NSLog(@"%d", messages.count);
for (int i=0; i<messages.count; i++)
{
NSString *data = [messages objectAtIndex:i];
NSLog(@"\n Data = %@",data);
}
}
精彩评论