无法将我的类的 NSMutableArray 保存到文件 (IOS) [英] Unable to save NSMutableArray of my class to file (IOS)

查看:56
本文介绍了无法将我的类的 NSMutableArray 保存到文件 (IOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法找出为什么我的代码不起作用.请帮助某人.

Can't find out why my code doesn't work. Please help someone.

我创建了自己的类,实现了 NSCoding 协议.不知道我错过了什么或错了什么.

I created my own class, implemented NSCoding protocol. Do not know what i miss or wrong.

这是保存代码

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"Currency.plist"]; 

Item * item = [[Item alloc] init];
item.x = 3; item.y = 5; item.type = (TType) 3; item.isSelected = NO;

NSMutableArray * array = [[NSMutableArray alloc] init];
[array addObject:item];

[array fileName atomically:YES]  // ( Doesn't Save the file ,returns NO);

这是我班级的代码*.h*

#import <Foundation/Foundation.h> 

enum TType 
{
    kNone = 0, 
    KFirst = 1,
    ....
}; 

@interface Item : NSObject <NSCoding>{

}  

@property (nonatomic) int x;
@property (nonatomic) int y;
@property (nonatomic) enum TType type;
@property (nonatomic) BOOL isSelected;

@end

.m

@implementation Item
@synthesize x, y , type , isSelected;

#pragma mark NSCoding Protocol

- (void)encodeWithCoder:(NSCoder *)encoder;
{
  [encoder encodeInt32:[self x] forKey:@"x"];
  [encoder encodeInt32:[self y] forKey:@"y"];
  [encoder encodeInt32:[self type] forKey:@"type"];
  [encoder encodeBool:[self isSelected] forKey:@"isSelected"];
}

- (id)initWithCoder:(NSCoder *)decoder;
{
    if ( ![super init] )
        return nil;

    [self setX:[decoder decodeInt32ForKey:@"x"]];
    [self setY:[decoder decodeInt32ForKey:@"y"]];
    [self setType:(TType)[decoder decodeInt32ForKey:@"color"]];
    [self setIsSelected:[decoder decodeBoolForKey:@"isSelected"]];

    return self;
}

@end

推荐答案

我想您会在以下位置找到答案:符合 nscoding 的对象不会写入文件

I think you'll find your answer at: objects conforming to nscoding will not writetofile

即您不能将 Item 类序列化为属性列表,因为它不是属性列表对象 (NSString, NSData, >NSArrayNSDictionary).

i.e. you can't serialize your Item class to a property list, since it isn't a property list object (NSString, NSData, NSArray, or NSDictionary).

请参阅 writeToFile:atomically::

这个方法在写出文件之前递归地验证所有包含的对象是属性列表对象,如果所有对象都不是属性列表对象,则返回NO,因为结果文件不会是一个有效的属性列表.

This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

这篇关于无法将我的类的 NSMutableArray 保存到文件 (IOS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆