I've started programming an iPhone app using CoreData and trying to make my codebase as maintainable as possible. Therefore I would like to avoid hard-coded strings such as:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", aName];
Instead I would like to be able to write something like:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", Person.name, aName];
That way I would get the compiler to check whether name
is a property of the entity Person
and avoid spelling mistakes.
With this code though I'm getting the following error at compile time:
Property name
not found on object of type Person
Person
being of type NSManagedObject
and automatically generated by Xcode from my MyApp.xcdatamodeld
.
name
is a simple string attribute of the entity Person
I've googled up and SOed up quite a lot already for an answer to this specific issue. I've also tried using property_getName
and NSPropertyDescription
with not luck so far.
Thanks in advance for you help,
Joss.
If you do use Mogenerator, per Kendall's excellent suggestion, in the auto-generated classes you will get three struct
s declared in the header - EntityNameAttributes
, EntityNameRelationships
, and EntityNameFetchedProperties
. So for instance, if your entity is named Person
, and had an attribute name
, you could get access to the key using PersonAttributes.name
. This would allow you to avoid having hard-coded key names in your application code.
First of all, Person.name
does not exist because "name" is a property of a person instance, not a class level property.
I'm not sure there's a really clear path from a compiler-checked method name to a string. You can always use lower level methods to access method signatures from a class and get strings from them, but the starting point for those is an un-checked string (either C or ObjC).
In general use of predicates will give you errors if you get the name wrong, so any testing that uses a predicate will verify you got the method name correct.
You should be using Mogenerator to generate data objects for use with your model. In that case you could look into changing the templates to add a method called something like "stringForMethodNamed*Name*" and include that as one of the parameters in the formatted predicate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With