Delete oldest file in directory iOS - ios

For some reason this method that I have written doesn't get rid of the oldest file in a directory even though everything seems fine from a logic point of view. Is there something subtle I am missing?
+(void)removeOldestFileFromDir:(NSURL *)dir forFileManager:(NSFileManager *)fm{
NSError *error = nil;
NSArray *contents = [fm contentsOfDirectoryAtPath:[dir path] error:&error];
NSArray *jpgFiles = [contents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self ENDSWITH '.jpg'"]];
NSDate *oldest = [NSDate date];
NSString *oldestFileName = nil;
for (NSString *f in jpgFiles) {
NSString *photoPath = [[dir path] stringByAppendingPathComponent:f];
NSDate *created = [[fm attributesOfItemAtPath:photoPath error:&error] objectForKey:#"NSFileCreationDate"];
if([created compare:oldest] == NSOrderedAscending){
oldestFileName = [NSString stringWithString:photoPath];
}
}
[fm removeItemAtPath:oldestFileName error:&error];
}
I've checked the error and it's alway (null) and the file that gets deleting is seemingly random - sometimes it's the newest, sometimes it's another one.

You forget to set oldest variable inside of your if.
It should be like that:
if([created compare:oldest] == NSOrderedAscending){
oldestFileName = [NSString stringWithString:photoPath];
oldest = created; // !!! This is what is missing
}

Related

edit core data model objects in a loop

I am trying to edit existing objects in Core Data storage. When i edit each object's attribute without a loop this works fine, but when I try to do it in a for loop, only my last object gets new attributes.
Here is the code I use to edit objects without a loop. This code works fine):
NSFetchRequest *songsRefreshRequest = [[NSFetchRequest alloc] initWithEntityName:#"Music"];
songsRefreshRequest.predicate = nil;
songsRefreshRequest.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"name"
ascending:YES
selector:#selector(localizedStandardCompare:)]];
NSError *frError;
NSArray *fetchedSongs = [self.context executeFetchRequest:songsRefreshRequest error:&frError];
fetchedSongs ? : NSLog(#"Error in fetch while refreshing songs: %#", [frError localizedDescription]);
NSString *song1path = [[NSBundle mainBundle] pathForResource:#"Beautiful-birds-song-in-the-morning" ofType:#"mp3"];
NSString *song2path = [[NSBundle mainBundle] pathForResource:#"Birds-singing-relaxation" ofType:#"mp3"];
NSString *song3path = [[NSBundle mainBundle] pathForResource:#"Morning Melody" ofType:#"mp3"];
Music *song1 = (Music *) [fetchedSongs objectAtIndex:0];
Music *song2 = (Music *) [fetchedSongs objectAtIndex:1];
Music *song3 = (Music *) [fetchedSongs objectAtIndex:2];
song1.name = #"Beautiful-birds-song-in-the-morning";
song2.name = #"Birds-singing-relaxation";
song3.name = #"Morning Melody";
song1.path = song1path;
song2.path = song2path;
song3.path = song3path;
Here is the code I use to edit song's attributes in a loop (code below somehow edit a path for only the last object (song3 in my case), other object's path attribute becomes NULL. And I can't figure out why):
for (Music *iterSong in fetchedSongs){
NSString *iterSongName = [iterSong valueForKey:#"name"];
iterSong.path = [[NSBundle mainBundle] pathForResource: iterSongName ofType:#"mp3"];
}
I have already tried to change for each to for (int i=0; i<[fetchedSongs count]; i++) this didn't help. Cycle repeats as many times as many songs are in the model and only changes the last song's path. Appreciate any help, thanks in advance!
P.S. The whole loop code:
for (Music *iterSong in fetchedSongs){
//Music *iterSong = (Music*) [fetchedSongs objectAtIndex:i];
NSLog(#"inerSong.name = %#", iterSong.name);
NSLog(#"inerSong.oldPath = %#", iterSong.path);
NSString *iterSongName = [iterSong valueForKey:#"name"];
NSString *iterSongPath = [[NSBundle mainBundle] pathForResource: iterSongName ofType:#"mp3"];
NSLog(#"iterSongPath (string) = %#", iterSongPath);
iterSong.path = iterSongPath;
NSLog(#"iterSong.newPath = %#", iterSong.path);
}
if ([self.context hasChanges]){
NSError *error;
if (![self.context save:&error]){
NSLog(#"error while saving context after refreshing song paths: %#", [error localizedDescription]);
}
}
First, I assume you run that loop inside the NSManagedObjectContext performBlock method. Second, you need to save your changes to your NSManagedObjects context after you edit your objects.
Objective-C:
NSError *error = nil;
if ([[self managedObjectContext] save:&error] == NO) {
NSAssert(NO, #"Error saving context: %#\n%#", [error localizedDescription], [error userInfo]);
}
Swift:
do {
try managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
Problem solved this way:
I removed all the hyphens from files' names. And the code started to work fine with the same loop. Also I converted files from mp3 to wav. But I suppose that problem existed because file can't include hyphen in its name.
Thanks everyone who answered!

Populated array not giving expected results

I've done a lot of object oriented programming in Java but im pretty new to objective C.
Am I doing the following properly.
Package.h
#interface Packages : NSObject
#property (nonatomic) NSArray *pictureArray;
#property (nonatomic) NSString *folderPath;
- (id)initWithPath:(NSString *)path;
-(NSArray *)getPackageItems;
-(NSString *)getFolderPath;
#end
Package.m
#implementation Packages
- (id)initWithPath:(NSString *)path
{
self = [super init];
if (self)
{
NSString *folderPath = [NSString stringWithFormat:#"%#/Objects/%#", [[NSBundle mainBundle] bundlePath], path]; //Path
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error: nil];
self.pictureArray = [fileList filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"pathExtension IN %#", #"png", #"(content BEGINSWITH %#)", #"object_"]];
}
for (NSString *s in self.pictureArray) {
NSLog(#"%#", s);
}
return self;
}
-(NSArray *)getPackageItems{
return self.pictureArray;
}
-(NSString *)getFolderPath{
return self.folderPath;
}
#end
Code in question inside the viewdidload of one of my views
NSMutableArray *packages = [[NSMutableArray alloc] init];
for(id key in temp){
NSLog(#"key=%# value=%#", key, [temp objectForKey:key]);
Packages *tmp = [[Packages alloc] initWithPath:[temp objectForKey:key]];
[packages addObject:tmp];
}
so this for loop is iterating over a plist that I have. A series of paths.
for each path, it is creating an instance of Packages and adding it to an array of packages.
However, when do I do this
NSArray *something = [packages[1] getPackageItems];
I get an empty result back no matter what!
and even when I do this
NSLog(#"%#", [packages[0] getFolderPath]);
It prints out null.
What am I doing wrong.
EDIT
This is how the picture folder looks like
The code to pull it use to work when all of the pictures where in the Objects directory without any of the sub directories. I hope I edited the code properly to handle the sub dir
Edit 2
NSError *error;
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.folderPath error: &error];
NSLog(#"%#, %#", fileList , error);
on the line
NSString *folderPath = [NSString stringWithFormat:#"%#/Objects", [[NSBundle mainBundle] bundlePath], path]; //Path
which successfully prints
2014-03-23 21:25:32.200 ScrollBar[4475:60b] (
"object_eyes_0_0.png",
"object_eyes_10_1.png",
"object_eyes_10_2.png",
"object_eyes_10_3.png",
"object_eyes_10_4.png",
"object_eyes_10_5.png",
"object_eyes_10_6.png",
"object_eyes_10_7.png",
When I do
NSString *folderPath = [NSString stringWithFormat:#"%#/Objects/%#/objects", [[NSBundle mainBundle] bundlePath], path]; //Path
which outputs
2014-03-23 21:27:46.951 ScrollBar[4496:60b] (null), Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x8e2dda0 {NSUnderlyingError=0x8e2d020 "The operation couldn’t be completed. No such file or directory", NSFilePath=/Users/dev/Library/Application Support/iPhone Simulator/7.1/Applications/8B55D440-5727-471E-9BCC-1513C190740E/ScrollBar.app/Objects/object_eye_0_0/objects, NSUserStringVariant=(
Folder
)}
But as you can see in the image above, the file structure does exist.
Solution:
I accepted an answer even though it wasnt the real answer, it was the clear path to find out what was wrong.
The problem was that you can not have referenced folders containing sub folders using the code provided. I just many folders.
in your initWithPath:, you have NSString *folderPath = which declare a local variable and assign some value to it. However you did not save the value so self.folderPath is nil
- (id)initWithPath:(NSString *)path
{
self = [super init];
if (self)
{
self.folderPath = [NSString stringWithFormat:#"%#/Objects/%#", [[NSBundle mainBundle] bundlePath], path];
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.folderPath error: nil];
self.pictureArray = [fileList filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"pathExtension IN %#", #"png", #"(content BEGINSWITH %#)", #"object_"]];
}
for (NSString *s in self.pictureArray) {
NSLog(#"%#", s);
}
return self;
}
for logging error
NSError *error;
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.folderPath error: &error];
NSLog(#"%#, %#", fileList , error);
NEVER do NSLog([Someclass someMethod]), use NSLog(#"%#", [Someclass someMethod]) instead

Looking for a Logic Solution to Build Dynamic Filepath in iOS

I have a file structure which is being built in the following manner.
1) Each user is provided an ID in MySQL database.
2) When user uploads an image from iphone the image is placed in the following directory:
`../images/[USER_ID]/[IMAGE_NUMBER].jpg`
3) In the path noted above, [IMAGE_NUMBER] is generated based upon the submission value. So the first image uploaded will be titled 1.jpg, the second as 2.jpg etc…
So to build a sample directory for the purposes of this question the structure could look something like this:
../images-->
../10/1.jpg
../10/2.jpg
../10/3.jpg
../11/4.jpg
../11/5.jpg
../10/6.jpg
../11/7.jpg
So in this case, User #10 uploaded 3 images, then logged out. Along comes User #11 and she uploads 2 images before logging out. And finally, User #10 logs back in and uploads another image.
Okay now that we have the summary of out the directories are being generated and images are dynamically input, let me get to the ultimate question. I would like to be able to display thumbnails of all the images on a view in the iphone when a user clicks a button that we will call btnRefresh
Here is the method that is associated with btnRefresh:
-(IBAction)btnRefreshTapped
{
[self refreshStream];
}
-(void)refreshStream {
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"stream",#"command",
nil]
onCompletion:^(NSDictionary *json) {
[self showStream:[json objectForKey:#"result"]];
}];
}
As you can see this is referencing the API sharedInstance here is that method:
+(API*)sharedInstance
{
static API *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:kAPIHost]];
});
return sharedInstance;
}
and finally we come full circle to the URLWithString value:
-(NSURL*)urlForImageWithId:(NSNumber*)IdPhoto isThumb:(BOOL)isThumb {
int IdValue = [[user objectForKey:#"id"] intValue];
NSString* urlString = [NSString stringWithFormat:#"%#/%#upload/%d/%#%#.jpg",
kAPIHost, kAPIPath, IdValue, IdPhoto, (isThumb)?#"-thumb":#""
];
return [NSURL URLWithString:urlString];
}
So, herein lies my problem. As this is currently being defined I can only see the images of the user that is logged into the app when they click btnRefresh. The other image locations show up as greyed out images due to the broken URLs. So, how can I redefine IdValue to cycle through available folders and pull the associated images for display?
I know this is a complex problem so thank you to putting some brainpower into a solution.
I don't know is it what you asking but you can get all files from the directory via this code:
NSArray *contents = [fileManager contentsOfDirectoryAtURL:YourURL
includingPropertiesForKeys:#[] // <-Add key/s if needed
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"pathExtension == 'jpg'"];
for (NSURL *fileURL in [contents filteredArrayUsingPredicate:predicate])
{
// Enumerate each .jpg file in directory
}
You can specify images directory and you should be able to find the images and get url to that.
The other way is recursively enumerate files in directory, it's more powerful and it can be amended to your requirement:
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:YOURURL
includingPropertiesForKeys:#[NSURLNameKey, NSURLIsDirectoryKey] // <-Add more key if needed
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:^BOOL(NSURL *url, NSError *error)
{
NSLog(#"Error %#", error);
}];
NSMutableArray *mutableFileURLs = [NSMutableArray array];
for (NSURL *fileURL in enumerator) {
NSString *filename;
[fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];
NSNumber *isDirectory;
[fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
if (![isDirectory boolValue]) {
[mutableFileURLs addObject:fileURL];
}
}
Hope one of those will be usefull for you.
Modifying what Greg just answered so that you don't have to iterate the array.
NSArray *paths = [fileManager contentsOfDirectoryAtURL:YourURL
includingPropertiesForKeys:#[]
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
[NSString stringWithFormat:
#"self ENDSWITH '/filename.jpg'"]];
NSArray *filteredArray = [paths filteredArrayUsingPredicate:predicate];
if ([newarray lastObject]) {
//you have your path here
}
filename.jpg is the IdPhoto.jpg in your code. This code with work because of the type of data you have. I have included "/" in filename.jpg so that there are no issues in detecting 110.jpg vs 10.jpg.

iOS - App crash without error during loop process

during a loop process, my App crash without error. The array count is equal to 175260. With profiler I don't have leaks, so I don't know why the App exit, maybe the CPU usage 100% during a lot of time?
Thank you for your help.
Just this code following crash the App :
for(unsigned int i = 0; i <14;i++)
{
if(findSensor[i]==YES)
{
for(unsigned int j = 1; j <[array count];j++)
{
#autoreleasepool {
if([[[[array objectAtIndex:j] componentsSeparatedByString:#";"] objectAtIndex:0] isEqualToString:[NSString stringWithFormat:#"%d",10*(i+1)]])
{
//Code here
}
}
}
}
}
The full code is :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/%#",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase];
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:fileName];
NSFileHandle *output = [NSFileHandle fileHandleForReadingAtPath:[NSString stringWithFormat:#"%#/%#10",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase]];
if(output == nil)
{
NSManagedObjectContext *context = [self managedObjectContext];
_recordlocal = [NSEntityDescription insertNewObjectForEntityForName:#"RECORD" inManagedObjectContext:context];
_recordlocal.date = [ibNavSettings interfaceSettings].selectedFileToDataBase;
NSData *inputData = [NSData dataWithData:[fh readDataToEndOfFile]];
NSString *inputString = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];
NSArray *array = [[NSArray alloc] initWithArray:[inputString componentsSeparatedByString:#"\n"]];
for(unsigned int i = 0; i <14;i++)
{
if(findSensor[i]==YES)
{
[[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:#"%#/%#%d",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase,10*(i+1)] contents:nil attributes:nil];
NSMutableString *saveString = [[NSMutableString alloc] init];
int count = 0;
for(unsigned int j = 1; j <[array count];j++)
{
#autoreleasepool {
if([[[[array objectAtIndex:j] componentsSeparatedByString:#";"] objectAtIndex:0] isEqualToString:[NSString stringWithFormat:#"%d",10*(i+1)]])
{
[saveString appendString:[array objectAtIndex:j]];
[saveString appendString:#"\n"];
if(i == 0)
count++;
progress++;
pourcent = progress/total;
load = pourcent*100;
if(load%5==0)
[self performSelectorInBackground:#selector(changeUI:)withObject:[NSNumber numberWithFloat:(pourcent)]];
}
}
}
[saveString writeToFile:[NSString stringWithFormat:#"%#/%#%d",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase,10*(i+1)] atomically:YES encoding:NSUTF8StringEncoding error:nil];
if(i == 0)
_recordlocal.count = [[NSNumber alloc] initWithInt:(count/50)];
}
}
_recordlocal.load = [[NSNumber alloc] initWithBool:YES];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Core data error %#, %#", error, [error userInfo]);
abort();
}
I would guess that your app is crashing without a readable exception because it is running out of available RAM, especially since you indicated that it is running through a large number of iterations.
For a test, I would recommend doing what Rikkles suggests with the autorelease pool. In addition, since the value of i (and as a result the comparison string) rarely changes, I would create that string outside the j loop as well. This would avoid the creation of a lot of extra strings laying around.
Beyond that, since it appears that you are looking for a string at the beginning of a string that is delimited by a semicolon, I would recommend instead of doing componentsSeparatedByString and then examining element zero that you use the NSString method hasPrefix to check for the condition you are looking for.
Here is an example:
for(unsigned int i = 0; i <14;i++)
{
NSString *searchString = [NSString stringWithFormat:#"%d;", 10*(i+1)];
if(findSensor[i]==YES)
{
for(unsigned int j = 1; j <[array count];j++)
{
if([[array objectAtIndex:j] hasPrefix:searchString])
{
//Code here
}
}
}
}
(I hope this compiles and runs, if it doesn't it should require more than minor tweaks. I am away from my Mac right now.)
If this doesn't help, then something going on inside //Code here must be the culprit.
Why are you creating [array count] autoreleasepools? What's the point of creating so many of them? It could crash because of that. Put the #autoreleasepool outside the for loop.
The only reason I could think that you would do that is if you create so many transient objects inside each iteration of the for loop that you'd want to get rid of them as soon as you got out of the iteration. But there are other ways to do that, including reusing those objects within each iteration.
First suggestion
Just use fast enumeration for the inner loop, you aren't actually using the index 'j' for anything
https://developer.apple.com/library/mac/documentation/General/Conceptual/DevPedia-CocoaCore/Enumeration.html
Second suggestion
Put some NSLog's in place, it will slow everything down, but you need to figure out what point you are failing at. That will help point everyone in the right direction.
Third suggestion
Actually use NSError objects and output their value if an error is thrown:
NSError *writeError = nil;
[saveString writeToFile:[NSString stringWithFormat:#"%#/%#%d",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase,10*(i+1)]
atomically:YES
encoding:NSUTF8StringEncoding
error:&writeError];
if(error != nil) NSLog(#"error writing file: %#", [[writeError userInfo]description]);
Fourth suggestion
You appear to try to be updating the UI from a background thread. This will not work or will cause a crash. UI code can only be called from a main thread. So dont do this:
[self performSelectorInBackground:#selector(changeUI:)withObject:[NSNumber numberWithFloat:(pourcent)]];
If you are already on a background thread this will probably crash because you are creating threads on threads on threads. You instead would want to call:
[self performSelectorOnMainThread:#selector(changeUI:)withObject:[NSNumber numberWithFloat:(pourcent)]];
Fifth suggestion
You may be going over the maximum length for NSString (it's big but I did it once on accident before). You should probably just be appending the file on each iteration of the loop instead, so you don't have an ever growing NSMutableString:
NSString *path = [NSString stringWithFormat:#"%#/%#%d",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase,10*(i+1)]
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:filePath];
NSData *newLine = [#"\n" dataUsingEncoding:NSUTF8StringEncoding];
for(NSString *rowString in array)
{
if([[[rowString componentsSeparatedByString:#";"] objectAtIndex:0] isEqualToString:[NSString stringWithFormat:#"%d",10*(i+1)]])
{
NSData *stringData = [rowString dataUsingEncoding:NSUTF8StringEncoding];
[fh truncateFileAtOffset:[fh seekToEndOfFile]];
[fh writeData:stringData];
[fh truncateFileAtOffset:[fh seekToEndOfFile]];
[fh writeData:newLine];
if(i == 0)
count++;
progress++;
pourcent = progress/total;
load = pourcent*100;
if(load%5==0)
[self performSelectorOnMainThread:#selector(changeUI:)withObject:[NSNumber numberWithFloat:(pourcent)]];
}
}
}
And this has the added benefit of helping you ditch the autoreleasepools
This was invalid
If your array does in fact have 175260 rows, that is probably your issue. You are looping using unsigned int as your index var. Unsigned ints in c only have a max value of 65535. Use an unsigned long int, max 4294967295.

iOS release not working as expected

I am using this code to get book names from a config.plist file. However my memory management is problematic. The '[dict release]' breaks the app completely and it exits.
The code works when the '[dict release]' is removed but it causes memory leaks as far as I can tell.
bnames is a global NSMutableArray
What am I doing wrong?
- (NSString *)loadBookname: (NSInteger) bookToLoad {
bookToLoad = [self bookOrder:bookToLoad];
//---get the path to the property list file---
plistFileNameConf = [[self documentsPath] stringByAppendingPathComponent:#"Config.plist"];
//---if the property list file can be found---
if ([[NSFileManager defaultManager] fileExistsAtPath:plistFileNameConf]) {
//---load the content of the property list file into a NSDictionary object---
dict = [[NSDictionary alloc] initWithContentsOfFile:plistFileNameConf];
bnames = [dict valueForKey:#"BookNames"];
[dict release];
}
else {
//---load the property list from the Resources folder---
NSString *pListPath = [[NSBundle mainBundle] pathForResource:#"Config" ofType:#"plist"];
dict = [[NSDictionary alloc] initWithContentsOfFile:pListPath];
bnames = [dict valueForKey:#"BookNames"];
[dict release];
}
plistFileNameConf = nil;
NSString *bookNameTemp;
bookNameTemp = [bnames objectAtIndex:bookToLoad - 1];
NSLog(#"bookName: %#", bookNameTemp);
return bookNameTemp;
}
You need to allocate your array properly:
bnames = [[NSArray alloc] initWithArray:[dict valueForKey:#"BookNames"]];
Double check that your dict returns the right data type.
There does not appear to be anything wrong with the way you allocate NSDictionary (although you could also use the [NSDictionary dictionaryWithContentsOfFile:] and save yourself having to worry about the release.
Either way I would suggest the issue is not with the [release] but probably the line BEFORE release:
bnames = [dict valueForKey:#"BookNames"];
a) Where is that allocated. I don't see an allocation or declaration of it anywhere?
b) What type of value do you expect back?
Put a break point on it and make sure your getting what you expect or anything.
If dict is not already a strong property, make it one. Then, use self.dict when assigning to it (and keep the release).
I've found what appears to be a better solution to the issue. This lets iOS manage the memory.
//---finds the path to the application's Documents directory---
- (NSString *) documentsPath {
NSLog(#"Start documentsPath");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
// NSLog(#"Found documentsPath 40");
NSLog(#"End documentsPath");
return documentsDir;
}
- (NSString *) configPath {
NSLog(#"Start configPath");
NSString *plistFileNameConf = [[self documentsPath] stringByAppendingPathComponent:#"Config.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistFileNameConf]) {
plistFileNameConf = [[NSBundle mainBundle] pathForResource:#"Config" ofType:#"plist"];
}
NSLog(#"plistFile: %#",plistFileNameConf);
NSLog(#"End configPath");
return plistFileNameConf;
}
The following calls the above code as necessary:
NSString *Choice;
NSArray *properties;
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:[self configPath]];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp) {
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
Choice = [temp objectForKey:#"Choice"];
properties = [temp objectForKey:Choice];

Resources