【问题标题】:How to get count of/iterate through all attributes that a NSManagedObject has?如何计算/迭代 NSManagedObject 具有的所有属性?
【发布时间】:2012-10-17 02:37:16
【问题描述】:

我在 Core Data 中将 NSManageObject 设置为实体。获取实体后,我希望能够提取所有属性并将它们放入 NSMutableArray 以填充 UITableView。

例如: 实体: 项目

属性: startDate(required);完成日期(可选);项目名称(必填);等等……

如何将所有这些放入 NSMutableArray?或者有没有更好的方法来填充 UITableView?

【问题讨论】:

    标签: ios uitableview core-data attributes


    【解决方案1】:

    您可以通过向 NSEntityDescription 询问其 NSAttributeDescription 对象来获取此信息:

    NSManagedObject *object = ...;
    NSEntityDescription *entity = [object entity];
    NSDictionary *attributes = [entity attributesByName];
    
    NSMutableArray *values = [NSMutableArray array];
    for (NSString *attributeName in attributes) {
      id value = [object valueForKey:attributeName];
      if (value != nil) {
        [values addObject:value];
      }
    }
    

    注意:这仅包含属性,不包含关系。如果您只需要关系值,可以使用-relationshipsByName。如果你想要属性和关系,你可以使用-propertiesByName

    决定这是否是一个好主意留给读者作为练习。

    【讨论】:

    • 作为一个附带问题,在您的 if (value != nil) 语句之后,我将如何检查它是否是 NSDate(isKindOfClass 不适用于我迄今为止尝试的方法)?或者我拥有的 Integer 16 Type 属性。
    • if ([value isKindOfClass:[NSDate class]]) { ... } 等。任何数字属性(整数、双精度、布尔值等)都将被装箱在 NSNumber 对象中。
    • 这就是我所缺少的,我正在做[value isKindOfClass:NSDate]。不知道我是怎么忘记[NSDate class] 的。感谢您的帮助!
    【解决方案2】:

    你不能只使用executeFetchRequest 来获取数组吗?

    NSEntityDescription *entity = [NSEntityDescription
                                       entityForName:@"Project"    
                                       inManagedObjectContext:someContext];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [someContext executeFetchRequest:fetchRequest error:&error];
    

    【讨论】:

    • 我有实体,我想将所有属性呈现给最终用户。
    【解决方案3】:

    编辑

    只需向您的实体添加一个返回非空属性数组的方法:

    - (NSMutableArray*)nonNullAttributes {
        NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithCapacity:0];
    
        //Pretend you have an attribute of startDate
        if (startDate && startDate != null) {
            [mutableArray addObject:startDate]
        }
    
        //Do this for all of your attributes.
        //You might want to convert the attributes to strings to allow for easy display in the tableview.
    
        return mutableArray;
    }
    

    您可以在您的 NSManagedObject 子类中添加它。然后,您可以使用数组的计数来知道有多少行。

    原始答案

    为什么还要费心将属性放入数组中?只需在填充 tableview 时直接从 Entity 访问它们。

    【讨论】:

    • 因为我知道的唯一其他方法是硬编码 cellForRowAtIndexPath: 像这样.... if (indexPath.row == 0 ) ((Project *) currentProject).startDate ... 等等对于每个属性。这取决于所有属性(甚至是可选属性)不为空。
    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 2019-02-11
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    相关资源
    最近更新 更多