기어가더라도 제대로

[DB-에러] Realm 쿼리(Invalid predicate expressions) 본문

만난 에러들

[DB-에러] Realm 쿼리(Invalid predicate expressions)

Damagucci-juice 2024. 12. 26. 15:27

배경

내부 DB에 저장되어있는 Realm Entity를 가져오는 과정에서 가져오는 형식에 관한 문제다.

보통 가져오는 상황

    private func fetchSome(
        _ dto: SomeDTO
    ) -> Results<SomeEntity> {
        return realm.objects(SomeEntity.self).where {
            $0.A == dto.A &&
            $0.B == dto.B &&
            $0.C == dto.C &&
            $0.D == dto.D
        }
    }

Entity와 DTO의 프로퍼티의 타입이 같다면 다음과 같이 가져온다.

두 타입간에 프로퍼티 타입의 차이가 없어서 큰 문제 없이 가져올 수 있었다.

문제가 된 상황

    private func fetchAnother(
        _ dto: AnotherDTO
    ) -> Results<AnotherEntity> {
        return realm.objects(AnotherEntity.self).where { 
                $0.A == dto.A &&
                $0.B == dto.B
        }
    }

이 코드를 했는데 이상하게 앱이 죽었다. 정말 이해가 안되는 상황이었다.

각 프로퍼티 간에 타입도 같았는데, 왜 이런 일이 벌어지는 건지 여전히 이해가 안가지만 버그는 발생했다.

*** Terminating app due to uncaught exception 'Invalid predicate expressions', reason: 'Predicate expressions must compare a keypath and another keypath or a constant value’

해결 방법

    private func fetchAnother(
        _ dto: AnotherDTO
    ) -> Results<AnotherEntity> {
        return realm.objects(PostEntity.self).filter(
            "%K == %@ AND %K == %@",
            "A", dto.A,
            "B", dto.B
        )
    }

NSPredicate 형식으로 하니까 문제 없이 잘 동작했다. 키 값을 명확하게 "%K"와 같이 밝혀야 함

배운점

Key 값으로 가져오려는 프로퍼티를 명확하게 하는 것이 필요하다. 

Comments