Unable to save NSMutableArray of my class to file (IOS)

两盒软妹~` 提交于 2019-12-11 00:42:19

问题


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

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

Here is saving code

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);

Here is the code of my class *.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

回答1:


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

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).

See the documentation for writeToFile:atomically::

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.



来源:https://stackoverflow.com/questions/9756861/unable-to-save-nsmutablearray-of-my-class-to-file-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!