在NSUserDefaults中存储填充了自定义对象的NSMutableArray - 崩溃

时间:2010-11-16 17:51:07

标签: iphone crash nsmutablearray nsuserdefaults store

编辑:这是一个工作版本。我通过NSCoding保存并从NSUserDefaults加载后,我能够在NSMUtableArray中检索我的对象。我认为重要的是,您不仅需要对数组进行反存档,还需要对其所有内容进行反存档。如您所见,我不仅要存储我的冻结对象的NSData,还要存储我的数组的NSData:

// My class "Freeze"
@interface Freeze : NSObject <NSCoding> // The NSCoding-protocoll is important!!
{
    NSMutableString *name;
}
@property(nonatomic, copy) NSMutableString *name;

-(void) InitString;
@end

@implementation Freeze
@synthesize name;

-(void) InitString {
    name = [[NSMutableString stringWithString:@"Some sentence... lalala"] retain];
}

// Method from NSCoding-protocol
- (void)encodeWithCoder:(NSCoder *)encoder
{
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.name forKey:@"name"];

}

// Method from NSCoding-protocol
- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if( self != nil )
    {
        //decode properties, other class vars
        self.name = [decoder decodeObjectForKey:@"name"];

    }
    return self;
}
@end




Freeze *freeze;
NSMutableArray *runes;
NSMutableArray *newRunes;


runes = [[NSMutableArray alloc] init];
newRunes = [[NSMutableArray alloc] init];

freeze = [[Freeze alloc] init];
[freeze InitString];
[runes addObject:freeze];

[self saveState];
[self restoreState];

Freeze *newFreeze = [[Freeze alloc] init];
newFreeze = [newRunes objectAtIndex:0];
NSString *String = [NSString stringWithString:newFreeze.name];
NSLog(@"%@", String);

//-----------------------------------------------------------------------------

- (void) saveState 
{    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];

    NSData* myClassData = [NSKeyedArchiver archivedDataWithRootObject:freeze];
    [defaults setObject:myClassData forKey:@"MyClass"];

    NSData* myClassArrayData = [NSKeyedArchiver archivedDataWithRootObject:runes];
    [defaults setObject:myClassArrayData forKey:@"MyClassArray"];

}

- (void) restoreState 
{    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];

    NSData* myClassData = [defaults objectForKey:@"MyClass"];
    freeze = [NSKeyedUnarchiver unarchiveObjectWithData:myClassData];

    NSData* myClassArrayData = [defaults objectForKey:@"MyClassArray"];    
    NSArray *savedMyClassArray = [NSKeyedUnarchiver unarchiveObjectWithData:myClassArrayData];
    if( savedMyClassArray != nil ) 
        newRunes = [[NSMutableArray alloc] initWithArray:savedMyClassArray];    
    else
    newRunes =  [[NSMutableArray alloc] init];
}

编辑:这是我之前收到的错误,它不再显示上面的更新版本。

它在最后崩溃,调试器显示以下错误: * *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [NSConcreteMutableData InitString]:无法识别的选择器发送到实例0x6b1fe20'*

此外,它说“NewFreeze”不是CFString类型。有人知道发生了什么事吗?我真的想保存我的对象。

2 个答案:

答案 0 :(得分:1)

问题是不允许将自定义类存储为Settings plist(NSUserDefaults)中的节点,因为数据存储在文件系统中而不是应用程序中的对象。设置应用程序(此数据也将可见)不知道“冻结”对象是什么。处理您想要做的事情的最佳方式是使用Core Data。

另请注意:当您尝试从Freeze数组初始化新的runes对象时,在方法结束时会导致您获得的错误,因为当您将对象放入runes数组首先将其封装为NSData对象,但是当你将其取出时,在将其设置为NewFreeze

之前不要将其解封

答案 1 :(得分:0)

您当然可以使用NSKeyedArchiver类保存自己的对象。 但是:

- (id)initWithCoder:(NSCoder *)decoder
{
    //self = [[Freeze alloc] init]; // I don't think you want to
                                    // allocate a new object here,
    self = [super init];
    if( self != nil )
    {
        //decode properties, other class vars
        self.name = [decoder decodeObjectForKey:@"name"];

    }
    return self;
}

就像之前提到的那样,你无法将它保存到NSUserDefaults。 但是,您可以将其保存到应用程序文档目录中的文件中。

编辑:这是我一年前写的一些代码作为测试。我认为这可能与您尝试做的非常接近。那里有一些与之无关的东西,比如从主捆绑中加载一个plist,但我会保留它以防万一有人觉得它有用。

HighScoresManager.h

#import <Foundation/Foundation.h>

@interface ScoreEntry : NSObject <NSCoding> 
{
    NSString *player;
    NSInteger score;
}
@property (nonatomic, retain) NSString *player;
@property (nonatomic, assign) NSInteger score;

+ (ScoreEntry *) entryWithScore:(NSInteger) score andPlayer:(NSString *)player;

@end


@interface HighScoresManager : NSObject
{
    NSMutableArray *m_Highscores;
}
@property (nonatomic, readonly) NSArray *highscores;

- (void) addScore: (NSInteger) score forPlayer:(NSString *)player;
- (void) addScoreEntry: (ScoreEntry *) entry;

@end

HighScoresManager.m

#import "HighScoresManager.h"

@implementation ScoreEntry
@synthesize player;
@synthesize score;

+ (ScoreEntry *) entryWithScore:(NSInteger) score andPlayer:(NSString *)player
{
    ScoreEntry *entry = [[[ScoreEntry alloc] init] autorelease];
    entry.score = score;
    entry.player = player;

    return entry;
}

+ (ScoreEntry *) entryWithNSDictionary:(NSDictionary *)dict
{
    ScoreEntry *entry = [[[ScoreEntry alloc] init] autorelease];
    entry.score = [[dict objectForKey:@"score"] intValue];
    entry.player = [dict objectForKey:@"player"];

    return entry;
}

- (void) encodeWithCoder: (NSCoder *) coder
{
    [coder encodeInteger:score forKey:@"score"];
    [coder encodeObject:player forKey:@"player"];
}

- (id) initWithCoder: (NSCoder *) decoder
{
    if( self = [super init] )
    {
        score = [decoder decodeIntForKey:@"score"];
        player = [[decoder decodeObjectForKey:@"player"] retain];
}

    return (self);
}

- (void) dealloc
{
    [player release];

    [super dealloc];
}

@end


@implementation HighScoresManager

- (BOOL) saveHighScores
{
    BOOL success = NO;

    if( m_Highscores )
    {
        NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO);

        NSString *path = [[[pathList objectAtIndex:0] stringByAppendingPathComponent:@"highscores.txt"] stringByExpandingTildeInPath];

        success = [NSKeyedArchiver archiveRootObject:m_Highscores toFile:path];
    }

    return success;
}

- (BOOL) loadHighScores
{
    BOOL success = NO;

    NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO);

    NSString *path = [[[pathList objectAtIndex:0] stringByAppendingPathComponent:@"highscores.txt"] stringByExpandingTildeInPath];

    if(m_Highscores)
    {
        [m_Highscores release];
    }

    m_Highscores = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if( m_Highscores )
    {
        [m_Highscores retain];
        success = YES;
    }
    else
    {
        m_Highscores = [[NSMutableArray alloc] init];
        success = NO;
    }

    // if empty, load default highscores from plist
    if([m_Highscores count] == 0)
    {
        NSString *resourcePath = [[NSBundle mainBundle] resourcePath];

        NSString *path = [[resourcePath stringByAppendingPathComponent:@"DefaultHighscores.plist"] stringByExpandingTildeInPath];

        NSDictionary *defaultHighscoresDict = [[NSDictionary alloc] initWithContentsOfFile:path];

        NSArray *defaultHighscores = [defaultHighscoresDict objectForKey:@"highscores"];

        for (NSDictionary *dict in defaultHighscores)
        {
            [m_Highscores addObject:[ScoreEntry entryWithNSDictionary:dict]];
        }

        [defaultHighscoresDict release];
    }

    return success;
}

- (id) init
{
    self = [super init];
    if(self)
    {
        [self loadHighScores];
    }
    return self;
}

- (NSArray *) highscores
{
    return (NSArray *) m_Highscores;
}

- (void) addScore: (NSInteger) score forPlayer:(NSString *)player
{
    [self addScoreEntry:[ScoreEntry entryWithScore:score andPlayer:player]];
}

- (void) addScoreEntry: (ScoreEntry *) entry
{
    [m_Highscores addObject:entry];
}

- (void) dealloc
{
    [self saveHighScores];
    [m_Highscores release];

    [super dealloc];
}

@end

也许我应该把文件上传到某个地方并在这里链接......无论如何,现在已经完成了。