Need generic FetchedResultsController builder (Swift)












0















I created a method to build an frc:



private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) 
-> NSFetchedResultsController<T>? {

let fetchRequest: NSFetchRequest = T.fetchRequest()
let sortDescriptor1 = NSSortDescriptor(key: sortKey, ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1]

searchContext.reset()

var frc: NSFetchedResultsController<T>? =
NSFetchedResultsController<T>(
fetchRequest: fetchRequest as! NSFetchRequest<T>,
managedObjectContext: searchContext,
sectionNameKeyPath: nil,
cacheName: nil)
frc!.delegate = self

try? frc!.performFetch()
return frc
}


I want to call something like this from within a closure:



self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


but I'm getting this error:




"Cannot convert value of type 'ObjectName.Type' to expected argument type 'NSManagedObject'".




Yet, ObjectName is the class name of an NSManagedObject. I tried myself
but eventually I just keep chasing errors in a circle.










share|improve this question





























    0















    I created a method to build an frc:



    private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) 
    -> NSFetchedResultsController<T>? {

    let fetchRequest: NSFetchRequest = T.fetchRequest()
    let sortDescriptor1 = NSSortDescriptor(key: sortKey, ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor1]

    searchContext.reset()

    var frc: NSFetchedResultsController<T>? =
    NSFetchedResultsController<T>(
    fetchRequest: fetchRequest as! NSFetchRequest<T>,
    managedObjectContext: searchContext,
    sectionNameKeyPath: nil,
    cacheName: nil)
    frc!.delegate = self

    try? frc!.performFetch()
    return frc
    }


    I want to call something like this from within a closure:



    self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


    but I'm getting this error:




    "Cannot convert value of type 'ObjectName.Type' to expected argument type 'NSManagedObject'".




    Yet, ObjectName is the class name of an NSManagedObject. I tried myself
    but eventually I just keep chasing errors in a circle.










    share|improve this question



























      0












      0








      0








      I created a method to build an frc:



      private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) 
      -> NSFetchedResultsController<T>? {

      let fetchRequest: NSFetchRequest = T.fetchRequest()
      let sortDescriptor1 = NSSortDescriptor(key: sortKey, ascending: true)
      fetchRequest.sortDescriptors = [sortDescriptor1]

      searchContext.reset()

      var frc: NSFetchedResultsController<T>? =
      NSFetchedResultsController<T>(
      fetchRequest: fetchRequest as! NSFetchRequest<T>,
      managedObjectContext: searchContext,
      sectionNameKeyPath: nil,
      cacheName: nil)
      frc!.delegate = self

      try? frc!.performFetch()
      return frc
      }


      I want to call something like this from within a closure:



      self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


      but I'm getting this error:




      "Cannot convert value of type 'ObjectName.Type' to expected argument type 'NSManagedObject'".




      Yet, ObjectName is the class name of an NSManagedObject. I tried myself
      but eventually I just keep chasing errors in a circle.










      share|improve this question
















      I created a method to build an frc:



      private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) 
      -> NSFetchedResultsController<T>? {

      let fetchRequest: NSFetchRequest = T.fetchRequest()
      let sortDescriptor1 = NSSortDescriptor(key: sortKey, ascending: true)
      fetchRequest.sortDescriptors = [sortDescriptor1]

      searchContext.reset()

      var frc: NSFetchedResultsController<T>? =
      NSFetchedResultsController<T>(
      fetchRequest: fetchRequest as! NSFetchRequest<T>,
      managedObjectContext: searchContext,
      sectionNameKeyPath: nil,
      cacheName: nil)
      frc!.delegate = self

      try? frc!.performFetch()
      return frc
      }


      I want to call something like this from within a closure:



      self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


      but I'm getting this error:




      "Cannot convert value of type 'ObjectName.Type' to expected argument type 'NSManagedObject'".




      Yet, ObjectName is the class name of an NSManagedObject. I tried myself
      but eventually I just keep chasing errors in a circle.







      swift core-data nsmanagedobjectmodel






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 1:59









      kit

      1,1063917




      1,1063917










      asked Nov 16 '18 at 1:44









      TubeTube

      33




      33
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Your function declaration doesn't mean quite what you think it does.



          private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) -> NSFetchedResultsController<T>? 


          This means that T must be a subclass of NSManagedObject, and that the first argument must be an instance of T. When you call it like this



          self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


          ...you're passing in the subclass as the first argument, when your declaration expects an instance.



          It's not hard to fix, because you don't need to include T as an argument. In general, Swift generics don't need you to pass the type as an argument-- the type comes from how the function is used. Drop that argument and rewrite the declaration as



          private func buildFRC<T:NSManagedObject>(sortKey: String) -> NSFetchedResultsController<T>? {


          Then call the function with something like



          self.frc: NSFetchedResultsController<ObjectName>? = self.buildFRC(sortKey: "trackName")


          Swift will figure out that T represents ObjectName in that call and the code will work.



          On a tangential note, your call to searchContext.reset() is kind of dangerous and probably not needed. If you fetch some objects from the context and then call this function later on, the reset will cause all of those previously fetched objects to become invalid. Using them would crash your app.






          share|improve this answer
























          • Thanks for your thoughtful replay. All is working now. I realize I need to study generics a bit more.

            – Tube
            Nov 17 '18 at 2:28











          • Unsure about reset: I am working directly from objects in contexts, so I figured a reset would be okay. Are you suggesting I batch delete them all instead?

            – Tube
            Nov 17 '18 at 2:41











          • Resetting and deleting are very different operations with very different effects. Resetting is unsafe unless no previously fetched objects are in memory. For example if your call this function twice, any objects from the first call should no longer be referenced anywhere in code. It’s likely to be a dangerous call unless you have a very clear understanding of its effects.

            – Tom Harrington
            Nov 17 '18 at 3:51











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53330297%2fneed-generic-fetchedresultscontroller-builder-swift%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Your function declaration doesn't mean quite what you think it does.



          private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) -> NSFetchedResultsController<T>? 


          This means that T must be a subclass of NSManagedObject, and that the first argument must be an instance of T. When you call it like this



          self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


          ...you're passing in the subclass as the first argument, when your declaration expects an instance.



          It's not hard to fix, because you don't need to include T as an argument. In general, Swift generics don't need you to pass the type as an argument-- the type comes from how the function is used. Drop that argument and rewrite the declaration as



          private func buildFRC<T:NSManagedObject>(sortKey: String) -> NSFetchedResultsController<T>? {


          Then call the function with something like



          self.frc: NSFetchedResultsController<ObjectName>? = self.buildFRC(sortKey: "trackName")


          Swift will figure out that T represents ObjectName in that call and the code will work.



          On a tangential note, your call to searchContext.reset() is kind of dangerous and probably not needed. If you fetch some objects from the context and then call this function later on, the reset will cause all of those previously fetched objects to become invalid. Using them would crash your app.






          share|improve this answer
























          • Thanks for your thoughtful replay. All is working now. I realize I need to study generics a bit more.

            – Tube
            Nov 17 '18 at 2:28











          • Unsure about reset: I am working directly from objects in contexts, so I figured a reset would be okay. Are you suggesting I batch delete them all instead?

            – Tube
            Nov 17 '18 at 2:41











          • Resetting and deleting are very different operations with very different effects. Resetting is unsafe unless no previously fetched objects are in memory. For example if your call this function twice, any objects from the first call should no longer be referenced anywhere in code. It’s likely to be a dangerous call unless you have a very clear understanding of its effects.

            – Tom Harrington
            Nov 17 '18 at 3:51
















          1














          Your function declaration doesn't mean quite what you think it does.



          private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) -> NSFetchedResultsController<T>? 


          This means that T must be a subclass of NSManagedObject, and that the first argument must be an instance of T. When you call it like this



          self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


          ...you're passing in the subclass as the first argument, when your declaration expects an instance.



          It's not hard to fix, because you don't need to include T as an argument. In general, Swift generics don't need you to pass the type as an argument-- the type comes from how the function is used. Drop that argument and rewrite the declaration as



          private func buildFRC<T:NSManagedObject>(sortKey: String) -> NSFetchedResultsController<T>? {


          Then call the function with something like



          self.frc: NSFetchedResultsController<ObjectName>? = self.buildFRC(sortKey: "trackName")


          Swift will figure out that T represents ObjectName in that call and the code will work.



          On a tangential note, your call to searchContext.reset() is kind of dangerous and probably not needed. If you fetch some objects from the context and then call this function later on, the reset will cause all of those previously fetched objects to become invalid. Using them would crash your app.






          share|improve this answer
























          • Thanks for your thoughtful replay. All is working now. I realize I need to study generics a bit more.

            – Tube
            Nov 17 '18 at 2:28











          • Unsure about reset: I am working directly from objects in contexts, so I figured a reset would be okay. Are you suggesting I batch delete them all instead?

            – Tube
            Nov 17 '18 at 2:41











          • Resetting and deleting are very different operations with very different effects. Resetting is unsafe unless no previously fetched objects are in memory. For example if your call this function twice, any objects from the first call should no longer be referenced anywhere in code. It’s likely to be a dangerous call unless you have a very clear understanding of its effects.

            – Tom Harrington
            Nov 17 '18 at 3:51














          1












          1








          1







          Your function declaration doesn't mean quite what you think it does.



          private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) -> NSFetchedResultsController<T>? 


          This means that T must be a subclass of NSManagedObject, and that the first argument must be an instance of T. When you call it like this



          self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


          ...you're passing in the subclass as the first argument, when your declaration expects an instance.



          It's not hard to fix, because you don't need to include T as an argument. In general, Swift generics don't need you to pass the type as an argument-- the type comes from how the function is used. Drop that argument and rewrite the declaration as



          private func buildFRC<T:NSManagedObject>(sortKey: String) -> NSFetchedResultsController<T>? {


          Then call the function with something like



          self.frc: NSFetchedResultsController<ObjectName>? = self.buildFRC(sortKey: "trackName")


          Swift will figure out that T represents ObjectName in that call and the code will work.



          On a tangential note, your call to searchContext.reset() is kind of dangerous and probably not needed. If you fetch some objects from the context and then call this function later on, the reset will cause all of those previously fetched objects to become invalid. Using them would crash your app.






          share|improve this answer













          Your function declaration doesn't mean quite what you think it does.



          private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) -> NSFetchedResultsController<T>? 


          This means that T must be a subclass of NSManagedObject, and that the first argument must be an instance of T. When you call it like this



          self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")


          ...you're passing in the subclass as the first argument, when your declaration expects an instance.



          It's not hard to fix, because you don't need to include T as an argument. In general, Swift generics don't need you to pass the type as an argument-- the type comes from how the function is used. Drop that argument and rewrite the declaration as



          private func buildFRC<T:NSManagedObject>(sortKey: String) -> NSFetchedResultsController<T>? {


          Then call the function with something like



          self.frc: NSFetchedResultsController<ObjectName>? = self.buildFRC(sortKey: "trackName")


          Swift will figure out that T represents ObjectName in that call and the code will work.



          On a tangential note, your call to searchContext.reset() is kind of dangerous and probably not needed. If you fetch some objects from the context and then call this function later on, the reset will cause all of those previously fetched objects to become invalid. Using them would crash your app.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '18 at 23:50









          Tom HarringtonTom Harrington

          53.7k5104131




          53.7k5104131













          • Thanks for your thoughtful replay. All is working now. I realize I need to study generics a bit more.

            – Tube
            Nov 17 '18 at 2:28











          • Unsure about reset: I am working directly from objects in contexts, so I figured a reset would be okay. Are you suggesting I batch delete them all instead?

            – Tube
            Nov 17 '18 at 2:41











          • Resetting and deleting are very different operations with very different effects. Resetting is unsafe unless no previously fetched objects are in memory. For example if your call this function twice, any objects from the first call should no longer be referenced anywhere in code. It’s likely to be a dangerous call unless you have a very clear understanding of its effects.

            – Tom Harrington
            Nov 17 '18 at 3:51



















          • Thanks for your thoughtful replay. All is working now. I realize I need to study generics a bit more.

            – Tube
            Nov 17 '18 at 2:28











          • Unsure about reset: I am working directly from objects in contexts, so I figured a reset would be okay. Are you suggesting I batch delete them all instead?

            – Tube
            Nov 17 '18 at 2:41











          • Resetting and deleting are very different operations with very different effects. Resetting is unsafe unless no previously fetched objects are in memory. For example if your call this function twice, any objects from the first call should no longer be referenced anywhere in code. It’s likely to be a dangerous call unless you have a very clear understanding of its effects.

            – Tom Harrington
            Nov 17 '18 at 3:51

















          Thanks for your thoughtful replay. All is working now. I realize I need to study generics a bit more.

          – Tube
          Nov 17 '18 at 2:28





          Thanks for your thoughtful replay. All is working now. I realize I need to study generics a bit more.

          – Tube
          Nov 17 '18 at 2:28













          Unsure about reset: I am working directly from objects in contexts, so I figured a reset would be okay. Are you suggesting I batch delete them all instead?

          – Tube
          Nov 17 '18 at 2:41





          Unsure about reset: I am working directly from objects in contexts, so I figured a reset would be okay. Are you suggesting I batch delete them all instead?

          – Tube
          Nov 17 '18 at 2:41













          Resetting and deleting are very different operations with very different effects. Resetting is unsafe unless no previously fetched objects are in memory. For example if your call this function twice, any objects from the first call should no longer be referenced anywhere in code. It’s likely to be a dangerous call unless you have a very clear understanding of its effects.

          – Tom Harrington
          Nov 17 '18 at 3:51





          Resetting and deleting are very different operations with very different effects. Resetting is unsafe unless no previously fetched objects are in memory. For example if your call this function twice, any objects from the first call should no longer be referenced anywhere in code. It’s likely to be a dangerous call unless you have a very clear understanding of its effects.

          – Tom Harrington
          Nov 17 '18 at 3:51




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53330297%2fneed-generic-fetchedresultscontroller-builder-swift%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Error while running script in elastic search , gateway timeout

          Adding quotations to stringified JSON object values