【问题标题】:How to get values from one of the Attributes using NSPredicate in Core Data如何在核心数据中使用 NSPredicate 从属性之一获取值
【发布时间】:2013-03-30 15:23:58
【问题描述】:

我有一个基于核心数据的项目。其中一个属性称为“日期”,我想从该属性中获取值,值以字符串“2013-03”开头,但我只能得到最新值,如字符串“2013-03-30”,如何将所有以“2013-03”开头的值放入NSArray?

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Database" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date beginsWith %@",value];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sortDescription = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
[fetchRequest setSortDescriptors:@[sortDescription]];

【问题讨论】:

    标签: iphone ios core-data nspredicate


    【解决方案1】:

    我自己解决 NSMutableArray *array = [[NSMutableArray alloc] init];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Database" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date beginsWith %@",value];
    [fetchRequest setPredicate:predicate];
    NSSortDescriptor *sortDescription = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    [fetchRequest setSortDescriptors:@[sortDescription]];
    
    NSError *fetchError = nil;
    NSArray *fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
    
    if ([fetchArray count] > 0)
    {
        for (Database *fetchResult in fetchArray)
        {
            [array addObject:fetchResult.date];
        }
    }
    return array;
    

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      相关资源
      最近更新 更多