How to convert an NSArray of NSManagedObjects to NSData

Posted by carok on Stack Overflow See other posts from Stack Overflow or by carok
Published on 2010-03-01T17:04:27Z Indexed on 2010/04/03 21:03 UTC
Read the original article Hit count: 624

Filed under:
|
|

Hi,

I'm new to Objective C and was wondering if anyone can help me.

I am using core data with a sqlite database to hold simple profile objects which have a name and a score attribute (both of which are of type NSString).

What I want to do is fetch the profiles and store them in an NSData object, please see my code below:

            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

            NSEntityDescription *entity = [NSEntityDescription entityForName:@"GamerProfile" inManagedObjectContext:managedObjectContext];
            [fetchRequest setEntity:entity];

            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
            NSArray *sortDecriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
            [fetchRequest setSortDescriptors:sortDecriptors];

            [sortDescriptor release];
            [sortDecriptors release];           

            NSError *error;
            NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:items];

            [self SendData:data];
            [fetchRequest release];

When I run the code I'm getting the error "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[GamerProfile encodeWithCoder:]: unrecognized selector sent to instance 0x3f4b530'"

I presume I have to add an encodeWithCoderClass to my core data NSManagedObject object (GamerProfile) but I'm not sure how to do this even after reading the documentation, My attempt at doing this is below. I'm not sure if I'm going along the right lines with this as get a warning stating "NSManagedObject" may not respond to '-encodeWithCoder'"

I would really, really appreciate it if someone could point me in the right direction!!

Thanks

C

Here is the code for my GamerProfile (CoreData NSManagedObject Object) with my attempt at adding an encodeWithCoder method...

Header File

#import <CoreData/CoreData.h>


@interface GamerProfile :  NSManagedObject <NSCoding>
{
}

@property (nonatomic, retain) NSString * GamerScore;
@property (nonatomic, retain) NSString * Name;

- (void)encodeWithCoder:(NSCoder *)coder;


@end

Code File

#import "GamerProfile.h"


@implementation GamerProfile 

@dynamic GamerScore;
@dynamic Name;

- (void)encodeWithCoder:(NSCoder *)coder {

    [super encodeWithCoder:coder];

    [coder encodeObject:GamerScore forKey:@"GamerScore"];
    [coder encodeObject:Name forKey:@"Name"];



}

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about iphone