ThomasGulli ThomasGulli - 1 year ago 81
Objective-C Question

Error when trying to save indexPath to NSUserDefaults

I am trying to save the indexPath for UICollectionView, but I get the following error:

libc++abi.dylib: terminating with uncaught exception of type NSException

My code is:
Save index path:

[[NSUserDefaults standardUserDefaults] setObject:indexPath forKey:@"CollectionIndex"];
[[NSUserDefaults standardUserDefaults] synchronize];

Load indexPath:

NSIndexPath *storedIndexPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"CollectionIndex"];

I have commented out code to find out which code that makes the error, and it is the code I am using to save the indexPath that creates the SIGABRT error.

Answer Source

Read the documentation of NSUserDefaults > setObjectForKey:

"The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects. See “What is a Property List?” in Property List Programming Guide."

To save an indexPath in the UserDefaults, you would have to make another representation, e.g. as a dictionary: (this uses newer objc literal syntax)

NSDictionary *dict = @{
    @"row": @(indexPath.row),  
    @"section": @(indexPath.section)