2013-04-07 19 views
0

我正在學習的Objective-C的時刻,到歸檔和卡住了與編碼和解碼。目標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:PROGRAME接收信號: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) 
+0

哪裏是你的'Foo'的@implementation?看來你已經將main()複製到你的問題兩次了。 – 2013-04-07 02:52:14

+0

@FirozeLafeer你是對的...感謝編輯它 – Bruce 2013-04-07 02:53:35

回答

0

是否使用ARC?

無論如何,你應該複製所有字符串(strValue = [[decoder decodeObjectForKey:@"test1"] copy];),以便保持對它們的不可變引用。否則,他們可以改變或消失在你的背後,事情將會變成kaboom(就像你看到的那樣)。

此外,像@一二三說,不要忘了self = [super init];

+0

即使你不復制'NSString',它永遠只是「消失」(前提是你'retain'它);只是意外地改變了它的價值。 – 2013-04-07 11:30:31

+0

在所示的代碼的情況下,給定的字符串沒有被保留或設置時複製。此外,它的安全總是'-copy',因爲你不知道如果傳入的對象是不可變與否,或者它可能是如何在你的背後改變。 – zadr 2013-04-08 07:46:17