views:

568

answers:

2

In the following code, I try to read data from a plist:

 -(void)readPreferences 
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray * myAppDefaults  = [defaults mutableArrayValueForKey:@"LastList"];
        myCustomObject * savedObject;
        NSUInteger i;
        for (i = 0; i < [myAppDefaults  count]; i++) 
        {
         NSArray * thisArray = [myAppDefaults  objectAtIndex:i];

         savedObject.value1 = [thisArray objectAtIndex:0];
         savedObject.value2 = [thisArray objectAtIndex:1];
         savedObject.value3 = [thisArray objectAtIndex:2];
         savedObject.value4 = [myAppDefaults  objectAtIndex:3];

         [objectsArray addObject:savedObject];
        }

    }

Somehow, when I try to set "savedObject.value1", I get an "EXC_BAD_ACCESS" error.

I realize this is quite likely basic memory management, or pointer/object kind of confusion, but I'm still learning. I hope someone can help me out here. Best regards Sjakelien

A: 

I don't see mutableArrayValueForKey in NSUserDefaults. Try arrayForKey: instead, that will give you NSArray*.

Seems that values returned from defaults are immutable (make sense as you're getting stuff from file).

Check the returned value from mutableArrayValueForKey, I suspect it's nil.

On second look your code does not make much sense. At no point you allocate savedObjects but you repeatedly insert it into array. Even the way you are extracting the values does not seem correct.

I would suggest looking at NSUserDefautls reference in Apple documentation, it has examples of basic usage.

stefanB
According to the documentation, mutableArrayValueForKey is "Available in iPhone OS 2.0 and later."Anyway, the returned value is not NIL. It contains 12 objects. I guess that's the problem.savedObject.value1 is an NSString, while the objectAtIndex:0 is an object. Maybe I should convert it somehow?
Sjakelien
All NSStrings (that is, NSString objects) are objects.
Peter Hosey
You are right about the not-making-sense of my code. Luckily, I returned here in time, to stop myself from asking another stupid question. Thanks!
Sjakelien
no question is stupid question
stefanB
+5  A: 

You haven't initialized savedObject at the time you set the value1 property. You will need to add:

savedObject = [[myCustomObject alloc] init];

before your for loop in order for it to be a valid object that you can set properties on.

Jason
You're so right! Thanks a lot!
Sjakelien
Don't forget to send release or autorelease to that object.
Peter Hosey