如何处理 Core Data 自定义方法 return 对象或 Obj C 中的 nil 或 Swift

How to handle Core Data custom methods what return an object or nil in Obj C or Swift

我有一个包含实体 PersonPersonEvent 的核心数据项目。 PersonEvent 和 Person 之间存在多对一关系 (personEvents)。 PersonEvent 的类型可以是 birth、death...a date... 在 Person 实体的 CoreDataProperties 文件中,我创建了一个名为 personBirthDate 的自定义方法,它应该 return 一个 NSDate。

-(NSDate *)personBirthDate
{
    NSDate * birthDate;

    // Use the relationship to get the related events
    NSArray *personEventsArray = [self.personEvents allObjects];

    // loop array to find an event of type birth
    // get the NSDate of the event in the PersonEvent
    // return the  birthDate;
    // code here ....

    return birthDate;
}

Person.personBirthDate在某些视图中与绑定一起使用。 代码不会崩溃,因为没有日期的事件不存在并且不会显示,但是正确地安静下来,xcode 抱怨 "nil returned from a method..." 如果没有类型为 birth 的事件链接到 Person,此方法将 return nil。

实现这个的最佳或更好的方法是什么?

让我把它作为一个答案而不是评论。

检查你的 class 接口,方法 return 类型似乎是 nonnull 类型,这意味着 return 值不应该是 nil

一个解决方案是将 nonnull 更改为 nullable,这表明 return 可以是 nil 值。

这是一篇讨论非空键和可为空键的苹果博客:link

主题片段:

_Nullable and _Nonnull. As you might expect, a_Nullable pointer may have a NULL or nil value, while a _Nonnull one should not. The compiler will tell you if you try to break the rules.