Reputation: 1233
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
Upvotes: 2
Views: 1657
Reputation: 27601
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.
Upvotes: 4