coredata问题获取数据

问题描述 投票:0回答:1

我只获得核心数据的最后记录?下面是我的代码。

NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;

NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Company"
                                                        inManagedObjectContext:context];
[object setValue:@"infosys" forKey:@"cname"];
[object setValue:@"01" forKey:@"compID"];
[object setValue:@"Pune" forKey:@"locaation"];

[object setValue:@"wipro" forKey:@"cname"];
[object setValue:@"02" forKey:@"compID"];
[object setValue:@"Mumbai" forKey:@"locaation"];

NSError *error;
if (![context save:&error]) {
    NSLog(@"Failed to save - error: %@", [error localizedDescription]);
}

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

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];


NSArray *result = [context executeFetchRequest:fetchRequest error:&error];

if (result.count<=0) {

    NSLog(@"No User Found");          
}
else{

    NSString *cname;        
    NSString *compID;   
    NSString *locaation;

    for (NSManagedObject  *obj in result) {

        cname=[obj valueForKey:@"cname"];
        compID=[obj valueForKey:@"compID"];
        locaation=[obj valueForKey:@"locaation"];


    }

    NSLog(@"Store Data = %@",[NSString stringWithFormat:@"%@ %@ %@",cname,compID,locaation]);        

}
ios objective-c core-data
1个回答
0
投票

添加这样的对象,

NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Company" inManagedObjectContext:context];
[object setValue:@"infosys" forKey:@"cname"];
[object setValue:@"01" forKey:@"compID"];
[object setValue:@"Pune" forKey:@"locaation"];


NSManagedObject *object2 = [NSEntityDescription insertNewObjectForEntityForName:@"Company" inManagedObjectContext:context];

[object2 setValue:@"wipro" forKey:@"cname"];
[object2 setValue:@"02" forKey:@"compID"];
[object2 setValue:@"Mumbai" forKey:@"locaation"];

NSError *error;
if (![context save:&error]) {
    NSLog(@"Failed to save - error: %@", [error localizedDescription]);
}

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

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];


NSArray *result = [context executeFetchRequest:fetchRequest error:&error];

if (result.count<=0) {

    NSLog(@"No User Found");

}
else{

    NSString *cname;
    NSString *compID;
    NSString *locaation;

    for (NSManagedObject  *obj in result) {

        cname=[obj valueForKey:@"cname"];
        compID=[obj valueForKey:@"compID"];
        locaation=[obj valueForKey:@"locaation"];

        NSLog(@"Store Data = %@",[NSString stringWithFormat:@"%@ %@ %@",cname,compID,locaation]);
    }



}
© www.soinside.com 2019 - 2024. All rights reserved.