如何在coredata中保存NSArray数据?

时间:2015-10-30 09:24:15

标签: ios core-data nsarray

我想将数据保存在NSArray的coredata中。我怎样才能做到这一点?

NSArray *fetchdata = [Lockbox arrayForKey:@"fetch"];   

在这里,我收到以下表格的数据:

enter image description here

如何在NSManageobject

中保存这些数据

这是我的尝试:

NSFetchRequest *fetchrequestforside=[NSFetchRequest fetchRequestWithEntityName:@"demo"];
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newDevice1 = [NSEntityDescription
    insertNewObjectForEntityForName:@"demo"
             inManagedObjectContext:context];

NSArray *fetchdata = [Lockbox arrayForKey:@"fetch"]; // 

for (int i =0;i<[fetchdata count];i++){
    NSString *Name = [[fetchdata objectAtIndex:i] objectForKey:@"name"];
    NSString *Websitename = [[fetchdata objectAtIndex:i] objectForKey:@"websitename"];
    NSString *Feedlink = [[fetchdata objectAtIndex:i] objectForKey:@"feedurl"];

    NSLog(@"value:%@,%@,%@",Name,Websitename,Feedlink);
    [newDevice1 setValue:Name  forKey:@"name"];

    [newDevice1 setValue:Websitename  forKey:@"websitename"];
    [newDevice1 setValue:Feedlink forKey:@"feedurl"];
    NSLog(@"value:%@,%@,%@",Name,Websitename,Feedlink);

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

但是使用这种技术我收到了一个错误。我该如何解决这个问题?

编辑: -

我收到此错误:

  

***因未捕获的异常而终止应用   'NSInvalidArgumentException',原因:' - [__ NSCFString objectForKey:]:   无法识别的选择器发送到实例0x7ff262520660'

3 个答案:

答案 0 :(得分:0)

您的代码将fetchdata数组的内容视为NSDictionary的实例,但LockBox仅显示支持字符串内容:

-(NSArray *)arrayForKey:(NSString *)key
{
    NSArray *array = nil;
    NSString *components = [self objectForKey:key];
    if (components)
        array = [NSArray arrayWithArray:[components componentsSeparatedByString:kDelimiter]];

    return array;
}

所以,你需要处理转换。你可能已经完成了处理原始阵列的部分......

但是,这就是为什么你得到错误,代码需要一个字典但实际上得到一个字符串

答案 1 :(得分:0)

你有一个看起来像这样的物体吗?

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface demo : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * websitename;
@property (nonatomic, retain) NSString * feedurl;

@end

创建这样的对象后(使用insertNewObjectForEntityForName)尝试像这样获取它:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
不过,我建议你坚持使用命名约定并称之为Demo。 干杯

答案 2 :(得分:-2)

我建议你使用真棒库MagicalRecord 它节省了很多时间,非常容易 这是它的教程 MagicalRecord Tutorial