2012-05-08 96 views
1

我试图为从UITableView被删除的行保存indexPathNSUSerDefaults尝试在NSUserDefaults中保存索引路径时出现错误

但我得到以下异常:

Attempt to insert non-property value '<NSIndexPath 0x834cc00> 2 indexes [0,1] 

我怎样才能解决这个和保存数据到用户默认设置在其他的方法访问它?

回答

5

您可以将其保存为两个浮点值,后来重建NSIndexPath:

所以保存indexPath.rowindexPath.column分别然后重新创建它:

[NSIndexPath indexPathForRow:inSection:] 
+1

'NSIndexPath'可以不只是两个值,它是一个值列表。从Apple文档:索引路径中的每个索引都表示从树中的一个节点到另一个更深的节点的子数组的索引。例如,索引路径1.4.3.2。在这种情况下,只需保存行和可能的部分即可。 – zaph

+0

有道理。我只在桌面视图的范围内使用它,所以也许对于他的问题,这将工作。 – rooster117

+0

感谢rooster117和Zaph ...它的工作! – iOSDev

2

添加类别NSIndexPath。这增加了两种方法,允许转换为NSArray或从NSArray转换。然后,您可以将其保存为默认值。

@implementation NSIndexPath (ArrayRepresentation) 

-(NSArray*)arrayRepresentation 
{ 
    NSMutableArray * result = [ NSMutableArray arrayWithCapacity:self.length ] ; 
    for(int index=0, count = self.length; index < count; ++index) 
    { 
     [ result addObject:[ NSNumber numberWithUnsignedInteger:[ self indexAtPosition:index ] ] ] ; 
    } 

    return result ; 
} 

+(NSIndexPath*)indexPathWithArrayRepresentation:(NSArray*)array 
{ 
    if (array.count == 0) { return nil ; } 

    // if array has too many items this will crash your app be careful 
    NSUInteger indexes[ array.count ] ; 
    for(int index=0, count = array.count; index < count; ++index) 
    { 
     indexes[ index ] = [ [ array objectAtIndex:index ] unsignedIntegerValue ] ; 
    } 

    return [ NSIndexPath indexPathWithIndexes:indexes length:array.count ] ; 
} 

@end 

我没有测试这一点,可能需要调试......

+1

只有几种类型的对象可以保存到属性列表/用户默认值中:数组,字符串,数字,数据以及其他几个 – nielsbot

0

可以保存到只NSUserDefaults的数组,字符串,数字,但不能NSIndexPath,所以你应该创建转换NSIndexPath的方法一个数组,然后将其保存到NSUserDefaults。

相关问题