I'm developing an iOS app and had perviously only been developing in android. In android its possible to store strings and string arrays in a resource file and then reference them later. This makes the actual code look much neater. Is there a way to do this in iOS?
You can store the data in a plist and then deserialize it into a dictionary (or even just an array, if you don't need to be flexible). For the documentation, see the class documentation on NSPropertyListSerialization at https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSPropertyListSerialization_Class/Reference/Reference.html#//apple_ref/occ/clm/NSPropertyListSerialization/propertyListWithData:options:format:error:
For example, if you had the following plist file named my_resources.plist:
<?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">
<dict>
<key>MyStringArray</key>
<array>
<string>String One</string>
<string>String Two</string>
</array>
</dict>
</plist>
You could load it (assuming it's in the bundle):
NSError* error = nil;
NSURL* resourceFile = [[NSBundle mainBundle] URLForResource:@"my_resources" withExtension:@"plist"];
NSData* resourceData = [NSData dataWithContentsOfURL:resourceFile options:0 error:&error];
if (resourceData) {
NSDictionary* resources = [NSPropertyListSerialization propertyListWithData:resourceData options:0 format:NULL error:&error];
if (resources) {
NSArray* myArray = resources[@"MyStringArray"];
NSString* stringOne = myArray[0]; // returns "String One"
NSString* stringTwo = myArray[1]; // returns "String Two"
// do something with the resources
} else {
NSLog(@"Error: Could not read plist data from %@: %@", resourceFile, error);
}
} else {
NSLog(@"Error: Could not read file data at %@: %@", resourceFile, error);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With