尝试在NSUserDefaults中保存索引路径时出错

时间:2012-05-08 03:41:44

标签: iphone objective-c ios nsuserdefaults nsindexpath

我正在尝试将indexPath中要删除的行UITableView保存到NSUSerDefaults

但我得到以下异常:

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

如何解决此问题并将数据保存到用户默认设置以便以其他方式访问它?

3 个答案:

答案 0 :(得分:5)

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

分别保存indexPath.rowindexPath.column,然后使用以下内容重新创建:

 [NSIndexPath indexPathForRow:inSection:]

答案 1 :(得分:2)

将类别添加到NSIndexPath。这增加了两种允许转换为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

我没有测试过,可能需要调试......

答案 2 :(得分:0)

您可以只向NSUserDefaults保存数组,字符串,数字,而不是NSIndexPath,因此您应该创建一个将NSIndexPath转换为数组的方法,然后将其保存到NSUserDefaults。

相关问题