NSMutableArray to NSData Conversion using NSUserDe

2019-09-20 06:05发布

问题:

As code shown below,it does not give me back my mutable array. I have 3 annotations in my mutable array, but once I close my app and open it again, it shows me 0 objects. I don't know why I am getting O objects while I am getting back my array!! any idea?

-(void)viewDidLoad
{
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];

    if([ud boolForKey:@"save-exist"])
    {
        NSMutableArray *udAnnotations=[[NSMutableArray alloc]initWithArray: [ud objectForKey:@"annotationsArray"]];
        NSLog(@"%d",[udAnnotations count]);
    }
    else
    {
        [self addAnno];
    }
}

-(void)addAnno
{
    [mapView addAnnotations:annotationArray];
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
    [ud setObject:annotationArray forKey:@"annotationsArray"];
    [ud setBool:YES forKey:@"save-exist"];
    [ud synchronize];
}

回答1:

You cannot save an MKAnnotation into NSUserDefaults. NSUserDefaults is a property list; only properly list objects can be stored there. You will need to archive the MKAnnotation to NSData in order to save it in NSUserDefaults. Read the docs, and also see for example Need to archive CLLocation data.