尝试将 indexPath 保存到 NSUserDefaults 时出错 [英] Error when trying to save indexPath to NSUserDefaults

查看:75
本文介绍了尝试将 indexPath 保存到 NSUserDefaults 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 UICollectionView 保存 indexPath,但出现以下错误:

libc++abi.dylib:以 NSException 类型的未捕获异常终止

我的代码是:保存索引路径:

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

加载索引路径:

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

我已注释掉代码以找出导致错误的代码,正是我用来保存 indexPath 的代码导致了 SIGABRT 错误.

解决方案

阅读 NSUserDefaults > 文档setObjectForKey:

<块引用><块引用>

"value 参数只能是属性列表对象:NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary.对于 NSArray 和 NSDictionary 对象,它们的内容必须是属性列表对象.请参阅什么是属性列表?"在属性列表编程指南中."

要在 UserDefaults 中保存 indexPath,您必须进行另一种表示,例如作为字典:

[[NSUserDefaults standardUserDefaults] setObject:@{@"row": @(indexPath.row),@"section": @(indexPath.section)}forKey:@"集合索引"];

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.

解决方案

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:

[[NSUserDefaults standardUserDefaults] setObject:@{@"row": @(indexPath.row),
                                                   @"section": @(indexPath.section)}
                                          forKey:@"CollectionIndex"];

这篇关于尝试将 indexPath 保存到 NSUserDefaults 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆