0

私は現在、アーカイブまでの目的の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) 
4

2 に答える 2

2

-initWithCoder:オブジェクトを設定する前に呼び出す必要がある初期化メソッドです。[super init]Apple の「Archives and Seralizations Programming Guide」の例を参照してください。

于 2013-04-07T03:21:41.503 に答える
0

ARCを使用していますか?

とにかく、strValue = [[decoder decodeObjectForKey:@"test1"] copy];それらへの不変の参照を保持するために、すべての文字列 ( ) をコピーする必要があります。そうしないと、それらが変更されたり、背後で消えたりして、物事がカブームになる可能性があります (ご覧のとおり)。

また、@一二三が言ったように、忘れないでくださいself = [super init];

于 2013-04-07T05:37:06.457 に答える