The Man
The Man

Reputation: 1462

Saving Object's To Files

I have the following code that saves an object to a file...

-(int) saveObject: (id)object forKey: (NSString *) key 
{
    //save object into file

    NSLog(@"PRESENT");
    if(filePath == nil) 
    {
        [self setFilePath:nil];
    }

    mainDict = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
    if(mainDict == nil) 
    {
        mainDict = [[NSMutableDictionary alloc] init];
    }

    [mainDict setObject:object forKey:key];

    if(![mainDict writeToFile:filePath atomically:YES]) 
    {
        return 2; //ERROR could not write object to file
        if(object == nil) {
            return 3;
        }
        if(key == nil) {
            return 4;
        }
    } 
    else 
    {
        if(shouldUseCache == YES) {
            cacheStatus = 2; //New Caches need to be updated
        }
        return 1; //SUCCESS object saved to file
    }

    //RETURN KEY's
    // *1 SUCCESS object saved to file
    // *2 ERROR could not write object to file
    // *3 ERROR object variable = nil
    // *4 ERROR key variable = nil
}

As you can see the method should clearly return a number between 1 and 4 but when I call the method in my view controller I get 0???

The weirdest part is that I don't even receive the NSLog(@"Present") in my console???

What is the problem and what causes this???

Here is my simple view controller...

NSLog(@"%d",[mainDict saveObject:@"HELLO" forKey:@"foo"]);

My .h file as well...

#import <UIKit/UIKit.h>
#import "ObjectSaver.h"

@interface ViewController : UIViewController {
    ObjectSaver *mainDict;
}

Upvotes: 0

Views: 70

Answers (1)

Dima
Dima

Reputation: 23624

Just to start: this statement doesn't do anything:

 if(filePath == nil) {
     [self setFilePath:nil]; }

If your NSLog isn't getting hit, then the function doesn't get called at all. Have you put a breakpoint into the function and debugged to see if it is actually ever entered?

Also as the comments say, your function will currently never return 3 or return 4. For it to be able to do so, return 2 should be moved after those 2 if blocks so that it can be the default error if the other 2 are not valid.

Upvotes: 2

Related Questions