在Core数据中无法存储对象

时间:2014-04-21 20:14:53

标签: ios core-data

我的代码在这里我试图将对象列表添加到我的数组表单中,我试图将其添加到代码数据属性中。

#import "ViewController.h"
#import "model.h"
#import "coredataManager.h"

@interface ViewController ()
{
    NSMutableArray *entries;
}

@end

@implementation ViewController

- (void)viewDidLoad
{


    entries = [[NSMutableArray alloc]init];

    coredataManager *coreobj = [[coredataManager alloc]init];
    model *obj = [[model alloc]initWithContents:@"1" alternateLink:@"1" DownloadURL:@"1"];
        model *obj2 = [[model alloc]initWithContents:@"2" alternateLink:@"2" DownloadURL:@"2"];
        model *obj3 = [[model alloc]initWithContents:@"3" alternateLink:@"3" DownloadURL:@"3"];

    [entries addObject:obj];
    [entries addObject:obj2];
    [entries addObject:obj3];

    NSLog(@"%@",entries);

    [coreobj StoreValues:entries];



    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

我的NSObject类

#import <Foundation/Foundation.h>

@interface model : NSObject

@property(copy)NSString *filename;
@property(copy)NSString *alternatelink;
@property(copy)NSString *downloadurl;

-(id)initWithContents:(NSString *)Fname alternateLink :(NSString *) ALink DownloadURL :(NSString *)DURL;

@end

NSObject实施文件

#import "model.h"

@implementation model

@synthesize downloadurl,filename,alternatelink;


-(id)initWithContents:(NSString *)Fname alternateLink :(NSString *) ALink DownloadURL :(NSString *)DURL
{
    if ((self = [super init])) {
        downloadurl = [DURL copy];
        filename = [Fname copy];
        alternatelink = [ALink copy];
    }
    return self;
}


@end

存储在核心数据中的代码

-(void)StoreValues:(NSMutableArray *) sample
{
    Sample *value = [NSEntityDescription insertNewObjectForEntityForName:@"Sample"
                                                  inManagedObjectContext:self.managedObjectContext];
    for (int i=0;i<sample.count;i++)
    {
        model *obj=[sample objectAtIndex:i];
        value.url = obj.downloadurl;
        value.filename = obj.filename;
        value.alternate = obj.alternatelink;

    }

    NSError *error;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

}

但只有数组的最后一个值存储在核心数据中,任何人都可以指导我解决这个问题 提前谢谢。

1 个答案:

答案 0 :(得分:3)

在保存之前,您需要重写对象。这样做:

Sample *value;
for (int i=0;i<sample.count;i++)
{
    value = [NSEntityDescription insertNewObjectForEntityForName:@"Sample"
                                              inManagedObjectContext:self.managedObjectContext];
    model *obj=[sample objectAtIndex:i];
    value.url = obj.downloadurl;
    value.filename = obj.filename;
    value.alternate = obj.alternatelink;

    NSError *error;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

}

在每次迭代后保存对象并且不重写它。然后重新开始。