0

Take the following code, I have to remember what the key names are for my custom data models.

// define a sort descriptor
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"timeStamp"; ascending:YES];
NSArray *scArray = [[NSArray alloc]initWithObjects:descriptor, nil];

Is there no way that I can do something like, myCustomDataModel.timeStamp instead, like I do when I insert an entity into my store with my custom managedObjects? One reason to do it like this is reduce typing errors. (I forgot what the word is called, something along the line of type face? The word I was going for had the meaning of there being less errors due to compile time checking)

Pavan
  • 17,840
  • 8
  • 59
  • 100
  • Is your question about Core Data entities? Then it might be a duplicate of http://stackoverflow.com/questions/23473897/core-data-nspredicate-issue-using-constant-literals-as-names-of-properties – Martin R May 30 '14 at 19:22
  • As Mathias' answer to @MartinR's referenced question points out, you could use `mogenerator` to do what you're looking for. Most of the answers are pretty clumsy, but using `mogenerator` makes it pretty straight-forward. IMO, you should always use it whenever you're using CoreData. – David Berry May 30 '14 at 19:34

1 Answers1

0

Yes, you can do something like that using the function NSStringFromSelector. As long as your array is filled with objects from your myCustomDataModel class, and that class has a property called timeStamp, you can do this,

    NSString *sortString = NSStringFromSelector(@selector(timeStamp));
    NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:sortString ascending:YES];
    self.myArray = [self.myArray sortedArrayUsingDescriptors:@[sorter]];

If you misspell the name of the selector, you will get a "undeclared selector" warning from the compiler.

rdelmar
  • 103,982
  • 12
  • 207
  • 218