Swift Data Relationships 🚀 | SwiftData Tutorial | #2

Поделиться
HTML-код
  • Опубликовано: 19 июл 2024
  • ⏭️ Next Video: Filtering In SwiftData - • Easily Add Filtering I...
    ⏮️ Previous Video: Intro To SwiftData - • SwiftData For Beginner...
    ⚠️ The crash at 9:41 is a known issue & has a workaround also by calling modelContext.save() after the deletion of an item
    Relationships In SwiftData 🚀 | Adding Categories To A To-Do App, SwiftData Tutorial
    Build A To-Do List App using SwiftData (Swift Data Tutorials) - Free Course
    • SwiftData Todo List Ap...
    **********************************
    Timestamps:
    00:00 - Intro
    00:32 - 🚨🚨🚨Warning
    01:03 - What Is A One To Many Relationship
    02:11 - How To Setup A One To Many Relationship in SwiftData
    06:23 - How To Save Categories in SwiftData
    07:19 - How To Fetch Categories in SwiftData
    08:32 - How To Delete in SwiftData
    09:41 - Fixing A Crash With Relationship Deletions
    12:41 - How To Save Data One To Many Relationships in SwiftData
    19:44 - Update A Relationship In SwiftData
    23:20 - Handling empty states with SwiftData
    **********************************
    Now that we have SwiftData, you may be wondering. "How can I relationships in SwiftData". Don't worry I've got you. In this SwiftData Tutorial, I'll be showing you how to work with SwiftData Relationships specifically a one-to-many relationship in SwiftData.
    We'll be building categories for our SwiftUI To-Do App, and give users the capability to create new categories and attach them to a todo. We'll also take a look at how to CRUD operations with a SwiftData relationship so that we can update our categories.
    **********************************
    Check Out My Courses 👨🏽‍🏫
    Enjoy my teaching style? Check out my other courses on my website that may interest you, they range from beginner to advanced topics within iOS development.
    Link to Website
    tunds.dev/#courses
    **********************************
    Join the crew 🤝
    Want to help support the channel? Become a member with the join link below and get access to exclusive badges and stickers, as well as other perks that are coming soon.
    Become a channel member
    www.youtube.com/@tundsdev/join
    Support in other ways 💕
    You can support me for free and help the channel grow so that I can continue to make the best iOS development content for you by liking, commenting, subscribing, and hitting the notification bell.
    All of this really helps my channel grow and allows me to keep on making content for you. If you’re interested in subscribing to the channel then you can do so with the link below.
    Subscribe to the tundsdev RUclips channel
    ruclips.net/user/tundsdev?su...
    **********************************
    Download Source Code
    Interested in looking at the source code? Then check out the GitHub Repo below
    github.com/tunds/youtube-cont...
    **********************************
    EditorKeys
    View Editor Keys Amazing Products with the link below and use the discount code for 10% off any product
    www.editorskeys.com/tundsdev
    Get a 10% Discount Code on any product with the code below
    TUNDSDEV
    See my keyboard cover in action with my review below 👇🏾
    • Increase Your Xcode Pr...
    **********************************
    RØDE Wireless Mic
    amzn.to/3D5qo3V
    RØDE SmartLavPlus Microphone
    amzn.to/3DtVUdG
    2021 Apple MacBook Pro (16-inch, Apple M1 Pro chip with 10‑core CPU and 16‑core GPU, 16GB RAM, 1TB SSD) - Space Grey
    amzn.to/3Drc2fH
    Apple Magic Keyboard with Numeric Keypad (Wireless, Rechargeable)
    amzn.to/3VUctXh
    Apple Magic Mouse
    amzn.to/3sqXSoM
    Secretlab TITAN 2020 Charcoal Blue Gaming Chair
    amzn.to/3D2jVXI
    ErgoFoam Ergonomic Foot Rest for Under Desk
    amzn.to/3srJOLM
    Lumbar Support Pillow
    amzn.to/3eXVfrg
    Macbook Stand for Apple Macbook and All Notebooks
    amzn.to/3DqG7vR
    Portable Chair Green Screen Background
    amzn.to/3gG62GU
    **********************************
    #iosdev #iosdevelopment #swift #swiftlanguage #xcode #appdevelopment #mobileappdevelopment #iosappdevelopment #appdeveloper #iosprogramming #iosengineer #appdevelopmenttips #iosdevelopmenttips #swiftui

Комментарии • 58

  • @tundsdev
    @tundsdev  Год назад

    ⚠ The crash at 9:41 is a known issue & has a workaround also by calling modelContext.save() after the deletion of an item

    • @tundsdev
      @tundsdev  11 месяцев назад +3

      Starting from Xcode 15 Beta 6
      You’ll need to specify the delete rule parameter in the Macro i.e
      @Relationship(deleteRule: .nullify)

    • @chezchezchezchez
      @chezchezchezchez 11 месяцев назад

      @@tundsdev how do we upgrade our beta five to beta six? Thanks.

    • @tundsdev
      @tundsdev  11 месяцев назад

      You can either download a new beta from Apple Developer or use a handy app i’ll have a video on soon called xcodes.app which lets you manage different versions 👌🏾

  • @nileshjdarji
    @nileshjdarji 4 дня назад

    super awesome video. Love it.

  • @marcaupont9145
    @marcaupont9145 Год назад +1

    Solid tutorial and great explanations!! 💪🏾💪🏾

  • @SiamakAshrafi
    @SiamakAshrafi Год назад +1

    Thanks. Very helpful.

    • @tundsdev
      @tundsdev  Год назад

      Glad it was helpful!

  • @michanierebinski1423
    @michanierebinski1423 Год назад +1

    A great follow up

  • @abhishekthapliyal7933
    @abhishekthapliyal7933 Год назад +1

    This was really helpful, I was about to bang my head into a wall after the worst relationships examples given in WWDC23. Thanks a ton

    • @tundsdev
      @tundsdev  Год назад

      I walked, so you can run. Glad you enjoyed the video and check out the whole series in the description box 👌🏾

    • @abhishekthapliyal7933
      @abhishekthapliyal7933 Год назад

      sure 🤩

  • @cloftis130
    @cloftis130 Год назад

    Great video Tunds. I think the crash you are experiencing may be tied to the new autosave feature implemented with SwiftData. I can consistently get my code to crash by deleting after an insert. To solve this, after the code to perform an insert:
    .insert(task) or .insert(category)
    Place an explicit call to the modelContext to save inside a do...catch:
    do {
    try modelContext.save()
    } catch {
    fatalError("Fatal error saving in function/class \(error), \(error.localizedDescription)")
    }
    I know it's not ideal, but I can't get the app to crash anymore. Maybe Apple will fix this in future betas.

    • @tundsdev
      @tundsdev  Год назад

      This was the confirmed workaround by Apple in Xcode 15 Beta 2. Once it's been resolved there will be no need to do this anymore

  • @mkhasson97
    @mkhasson97 Год назад +3

    Nice video, could you perhaps complete the serie and add many to many relationships too? For example let's say insert sub-todo or I mean list into this list, I will really appreciate that. Thank you so much ❤

    • @tundsdev
      @tundsdev  Год назад +1

      Thanks for the idea! That would still be a One to many relationship, for many to many a tags functionality would work for that 👀

    • @aplutalobacz
      @aplutalobacz 9 месяцев назад

      @@tundsdevhow do we implement 2 models when one consists an array of other model. Imagin tag could have different variables and then ToDo event can consist an array of them? I have been trying to create this type of database- unfortunately without success:(

  • @jayelevy
    @jayelevy 10 месяцев назад

    One additional comment on this and I’m reluctant to share as I’m grateful for what you do!
    Having said that, the coding for this is confusing if you are following these videos in sequence. I completed the first video and then moved on to this. I assumed I could simply continue with the code base as we left at the end of the last video. Wrong assumption. I kept finding pieces of code that were either missing or changed from the first video. Finally realized during the segment when you added the save function that I’m missing a bunch of code. I need to scrap and start over using the git samples for this video. I think this could be explained better. I feel it is a logical progression to move from one video to the next while continuing the same project.
    I hope that makes sense.

    • @tundsdev
      @tundsdev  10 месяцев назад

      Hey,
      I’m pretty sure I reference that this video is built on top of a previous one and is part of a course 😅
      (Yep I do in the intro section & warning section)
      I highly suggest following the entire playlist/course which you can find a link to below
      ruclips.net/p/PLvUWi5tdh92wZ5_iDMcBpenwTgFNan9T7&si=DREJdYaDgntH0tEo

    • @jayelevy
      @jayelevy 10 месяцев назад

      Thanks for the follow-up. That is exactly my point. That is, if you are following along in sequence on the playlist, as I was, one would assume that the ending status of code in the prior video (eg, ContentView or CreateTodoView at the end of video 1) would be equivalent to the starting point when the next video (1:many relationships) starts. That is not the case and the continuity is lost. After I finish video 1, I need to figure out the delta’s for the starting point for video 2.
      Maybe I am missing something. Again, not complaining!! I’m super grateful for what you do. You do an awesome job explaining things. I love it. Just sharing what seems to be a confusing transition between vids.
      I’ll leave it alone now. I know what to expect! It’s all good… thanks again for your service to the SwiftUI community!! Cheers

    • @tundsdev
      @tundsdev  10 месяцев назад

      @@jayelevy I’m not too sure what else to here, for every video in this course. I provide starter files and final files in my GitHub repo so you can easily pickup and follow along. The only way around this is if I created a long video with everything combined which would be huge.
      Maybe i’ll start making it extra clear in my vids that you’ll need to watch previous videos and or get the starter files from GitHub to avoid confusion 👌🏾
      Because it is meant to flow between videos where you can pick stuff up, i think the problem here is that its not clear that you can use the starter files to dive into the code straight away

    • @jayelevy
      @jayelevy 10 месяцев назад

      Thanks for your responses. Now… I need to get back to the videos!! 🍻

  • @mrchumley
    @mrchumley Год назад

    Thanks for the video! Brilliant tutorial, but is there something missing just before 8:10? I couldn't see where you added the new buttons to the main view?

    • @tundsdev
      @tundsdev  Год назад

      Thanks and if you keep watching to when I save data you’ll see the SwiftUI code, also the final code is in the description box too. Since I wanted to keep this vid short 👌🏾

    • @mrchumley
      @mrchumley Год назад

      Fair enough and yes, I picked it up from your GitHub - thanks for sharing 🙂

  • @ChristopherDisdero
    @ChristopherDisdero Год назад

    Thanks for another great tutorial!
    Despite taking your advice and adding the code to set category.items = empty array and set title = empty string when adding a category, I'm still crashing when deleting a newly added category. The problem seems to be because we are trying to access the title property of a category item that may have already been removed due to the ForEach loop?
    Any ideas?

    • @tundsdev
      @tundsdev  Год назад

      Thanks & Hmmm I wasn’t getting this behaviour anymore with crashes after testing this out a few times. Like I said at the start with my warning it could be an Xcode Beta issue. I’d open up a feedback and post on the developer forums 👌🏾

  • @josephestrada4222
    @josephestrada4222 3 месяца назад

    My version of the button.
    // START - New ToDo button
    VStack {
    Spacer() // Push content to the right
    // New ToDo button
    Button(action: {
    showCreate.toggle()
    }) {
    HStack {
    Image(systemName: "plus.circle.fill")
    .foregroundColor(.blue) // Icon color
    Text("New ToDo")
    .foregroundColor(.blue) // Text color
    }
    .padding(.vertical, 10)
    .padding(.horizontal)
    .background(Color.white) // Button's background color
    .cornerRadius(20) // Pill shape
    .shadow(color: .gray, radius: 2, x: 0, y: 2) // Shadow for depth
    }
    .padding(.trailing, 180) // To match the floating button's right padding
    .padding(.bottom, 20) // To match the floating button's bottom padding
    }

  • @jayelevy
    @jayelevy 10 месяцев назад +1

    Yet another great set of videos! Thank you for what you do.
    I am getting an error “Type ‘Schema.Relationship.Option’ has no member ‘nullify’” in the Item model definition on the @Relationship line (code copied directly from your git). I’m wondering if this is a beta bug? Though, I’ve searched and see no reference to this. I’m stuck.

    • @tundsdev
      @tundsdev  10 месяцев назад

      Hey man thanks, glad you enjoyed it. Also as well I added a pinned comment with this fix also you can check out that pinned comment and the thread with any updates you’ll need to change 👌🏾

    • @jayelevy
      @jayelevy 10 месяцев назад

      Ah, thanks mate! My apologies… I didn’t see that embedded within the top pinned item.

    • @tundsdev
      @tundsdev  10 месяцев назад

      No worries tbh i will update the pinned tweet so its clearer

  • @Ride8715
    @Ride8715 10 месяцев назад

    Do you mind explaining the property wrappers? All of these new ones are throwing me for a loop? @Bindable vs @Query is the thing that is catching me off guard. So you create the model on the class with @Model but you link it with @Query? If you want to change something is that when @Bindable comes into play?
    Yes that helps! Thank you. Also real credit to you to respond to comments so quickly.

    • @tundsdev
      @tundsdev  10 месяцев назад

      Hey man sure
      @Query = This is a macro that allows us to execute queries to fetch data from SwiftData. Its part of SwiftData.
      @Bindable = This is part of the new Observation framework & allows us to listen to changes and make changes to classes marked with the new Observable macro you don’t want to use this unless you want to create some kind of state. By default the Model macro (i’ll get onto in a sec) uses this to allow you to update your SwiftData storage and listen to changes/make your UI react.
      @Model = This is part of SwiftData, it allows you to mark your models/schema that you’ll be working with and saving/fetching. So you mark your class with this macro to let SwiftData know this is your schema and your container to know this is what you’ll be working with
      Hope this helps

  • @Echaront
    @Echaront 18 дней назад

    In Xcode 15.4, I am encountering errors at 7:05. The error reads: "Struct 'ViewBuilder' requires that 'EmptyTableRowContent' conform to 'View'" and Static method 'buildExpression' requires that 'TextField' conform to 'TableRowContent'. It would be great if you could update the app using Xcode 15.4 for iOS 17.

    • @tundsdev
      @tundsdev  18 дней назад +1

      Hey can you download the final source code in the description box, i've ran project and the only thing that needs to be removed is the .nullify since there's no need to specify this anymore and also it's worth noting that this video was created when xcode 15 and swiftdata was still in beta.

    • @Echaront
      @Echaront 18 дней назад

      @@tundsdev fair enough. Thank you for your amazing content!

  • @akbar.n
    @akbar.n 10 месяцев назад

    Hello Brother,
    I have one Question ❓
    I want to provide an icon & color at the time of creating todo.
    For that i had created antother view which had all SFsymbols, which is presented in sheet from where I can select the icon & that icon should be selected on the create todo view. But i m not able to do that.
    I way I was able to achive that result was buy create a model for Icon, same as you did for category. But that will use extra resources on the app, because I had created the relationship for Icon with TODO. Not is not approprate.
    Because we have all icon in sheet & from that sheet we just want that which icon was selected & should add that icon name String into todo.
    We cant append icon into todo because we have not still created new todo.
    Home View → Create Todo View → Icon Sheet → Create Todo View
    If I have 10 to 20 icon I can make array in the Create Todo View & that will work. I can do that. But I cant pass selected icon from Icon Sheet to Create Todo View.
    Can you make a Video 🎞 in which we can you can add icon & color on create category or create todo view.
    And categories should also not be on create todo view. If they are with the page we are able to select. But if we move it to another sheet we are not able to select it from there. So please also extract category selection from another sheet. In real apps user has lot of categories.
    Video Explaination : ruclips.net/video/LQeDWEQf23E/видео.html
    Blog Link : noteplan.co/n/2D6DF362-6B45-4908-959C-106205FD4B99

  • @bobgilmore3224
    @bobgilmore3224 10 месяцев назад

    As of Xcode 15 beta... 4? 5?, the @relationship macro requires a deleteRule tag, i.e., at 5:01, you need...
    @Relationship(deleteRule: .nullify, inverse: \Category.items)
    (I just noticed that this is mentioned in the comment regarding the crash at 9:41, but I wasn't even looking at that that since I was seeing problems at 5:01.)

    • @tundsdev
      @tundsdev  10 месяцев назад

      👋🏾 yep both are mentioned in the pinned comments, i filmed this video using Xcode 15 b1 the delete rule changes were made from b6

  • @DavidM979
    @DavidM979 Год назад

    Github repo is missing from description

    • @tundsdev
      @tundsdev  Год назад

      It’s not missing its the link is there to all my 2023 content

  • @tundsdev
    @tundsdev  Год назад

    First person to spot the mistake in the intro wins nothing

    • @andresmade2853
      @andresmade2853 Год назад

      Upload the start up file lol

    • @tundsdev
      @tundsdev  Год назад +1

      That’s not the mistake, but those files should be in the repo now 👌🏾

    • @30guarino
      @30guarino Год назад

      You didn’t make an array of .modelContent[Items.self, Category.self] in the @main App view …

    • @cagrgider8320
      @cagrgider8320 Год назад +1

      You are saying "Swift Data" but it writes "Core Data" on the top right. Did I win nothing? :))

    • @tundsdev
      @tundsdev  Год назад

      You won nothing, yes

  • @lfan_tv
    @lfan_tv 2 месяца назад

    Nice video! and can I know the .onAppear{} and .onAppear(perform: {}) is exactly same?

  • @teakodo
    @teakodo 4 месяца назад

    Update the relationship by adding deleteRule:
    @Relationship(deleteRule: .nullify, inverse: \Category.items)

    • @tundsdev
      @tundsdev  4 месяца назад +1

      I explain this in the pinned comment, there were updates in the beta you can see all the updates in the pinned comment and replies

    • @teakodo
      @teakodo 4 месяца назад

      @@tundsdev thank you!

    • @evamartina9883
      @evamartina9883 2 месяца назад

      @@tundsdev hi sorry, i can't see the comment, looks you have changed the pin