Optional chaining strange behaviour #329

Closed
opened 2025-12-29 18:25:44 +01:00 by adam · 2 comments
Owner

Originally created by @spacedema on GitHub (May 21, 2020).

Hi!

Noticed strange behaviour while fetching from db, don't know if it is related to core store

// Ok
func getSomeId() -> String? {
  let transaction = DataStack.beginUnsafe()
  return try? transaction.fetchOne(From<Users>().where(\.id == myId))?.otherField?.id
}

// Not Ok, return nil
func getSomeId() -> String? {
  return try? DataStack.beginUnsafe().fetchOne(From<Users>().where(\.id == myId))?.otherField?.id
}
Originally created by @spacedema on GitHub (May 21, 2020). Hi! Noticed strange behaviour while fetching from db, don't know if it is related to core store ``` // Ok func getSomeId() -> String? { let transaction = DataStack.beginUnsafe() return try? transaction.fetchOne(From<Users>().where(\.id == myId))?.otherField?.id } // Not Ok, return nil func getSomeId() -> String? { return try? DataStack.beginUnsafe().fetchOne(From<Users>().where(\.id == myId))?.otherField?.id } ```
adam added the question label 2025-12-29 18:25:44 +01:00
adam closed this issue 2025-12-29 18:25:44 +01:00
Author
Owner

@JohnEstropia commented on GitHub (May 22, 2020):

My guess it that ARC releases the transaction earlier in the second code. If that's the case, you will probably experience the same thing in the first code when building release (optimized) builds.

You can try

return withExtendedLIfetime(DataStack.beginUnsafe()) { transaction in
    try? transaction.fetchOne(From<Users>().where(\.id == myId))?.otherField?.id
}
@JohnEstropia commented on GitHub (May 22, 2020): My guess it that ARC releases the transaction earlier in the second code. If that's the case, you will probably experience the same thing in the first code when building release (optimized) builds. You can try ```swift return withExtendedLIfetime(DataStack.beginUnsafe()) { transaction in try? transaction.fetchOne(From<Users>().where(\.id == myId))?.otherField?.id } ```
Author
Owner

@spacedema commented on GitHub (May 22, 2020):

Thanks for the answer, will check it in release build

@spacedema commented on GitHub (May 22, 2020): Thanks for the answer, will check it in release build
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/CoreStore-JohnEstropia#329