目标c - 存档编码和解码的麻烦

时间:2013-04-07 02:46:41

标签: objective-c nscoding

目前我正在学习objective-c,直到归档并陷入编码和解码。

这是我的代码。

 #import <Foundation/Foundation.h>

    @interface Foo : NSObject<NSCoding>

    @property (copy, nonatomic) NSString *strVal;
    @property int intVal;
    @property float floatVal;

    @end

    #import "Foo.h"

@implementation Foo

@synthesize intVal, floatVal, strVal;

-(void) encodeWithCoder: (NSCoder *) encoder
{
    [encoder encodeObject: strVal forKey: @"test1"];
    [encoder encodeInt: intVal forKey: @"test2"];
    [encoder encodeFloat: floatVal forKey: @"test3"];
}

-(id) initWithCoder: (NSCoder *) decoder
{
    strVal = [decoder decodeObjectForKey: @"test1"];
    intVal = [decoder decodeIntForKey: @"test2"];
    floatVal = [decoder decodeFloatForKey: @"test3"];

    return self;
}

@end


    #import "Foo.h"

    int main (int argc, const char * argv[])
    {

        @autoreleasepool {
            Foo *myFoo1 = [[Foo alloc] init];
            Foo *myFoo2;

            [myFoo1 setStrVal : @"bill"];
            [myFoo1 setIntVal : 2];
            [myFoo1 setFloatVal: 3.4];

            [NSKeyedArchiver archiveRootObject: myFoo1 toFile: @"foo.arch"];

            myFoo2 = [NSKeyedUnarchiver unarchiveObjectWithFile: @"foo.arch"];

            NSLog(@"%@", [myFoo2 strVal]);
        }
        return 0;
    }

解码适用于int和float,但是当我尝试解码NSString对象时。我得到以下错误,我不知道它...

线程1:程序收到信号:EXC_BAD_ACESS“

GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug 15 16:03:10 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys000
[Switching to process 2457 thread 0x0]
sharedlibrary apply-load-rules all
Current language:  auto; currently objective-c
(gdb) 

2 个答案:

答案 0 :(得分:2)

-initWithCoder:是一种初始化方法,您在设置对象之前必须调用[super init]。请参阅Apple的“Archives and Seralizations Programming Guide”中的示例。

答案 1 :(得分:0)

您使用ARC吗?

无论如何,您应该复制所有字符串(strValue = [[decoder decodeObjectForKey:@"test1"] copy];),以便保留对它们的不可变引用。否则,他们可以改变或消失在你的背后,事情会变成kaboom(就像你看到的那样)。

另外,就像@一二三说的那样,不要忘记self = [super init];