I have several core data entities that contains a bunch of empty NSString
properties.
I parse some XML and set the properties I can get a hold of and would like to set the "empty" ones to "n/a" as in "not available". So if my XML does not contain the values it sort of tidy up the Entity by giving it a "n/a" string I can test for la开发者_JAVA百科ter on, also should one of these make it to a UILabel it will not display (null) .. which leads me to my question:
I do this to test if the property on the Entity is already sat, is nil or is empty:
for(NSString *s in allPossibleStrings) {
if([[f valueForKey:s] isKindOfClass:[NSString class]] && [[f valueForKey:s] isEqualToString:@""]) {
[f setValue:@"n/a" forKey:s];
}
if ([[f valueForKey:s] isKindOfClass:[NSString class]] && [f valueForKey:s] == nil) {
[f setValue:@"n/a" forKey:s];
}
}
It turns out however that I still end up with a lot of values being displayed as (null).
So I was thinking can the property be something else than @""
empty or (nil)
I believe the NSManagedObject should be KVC compliant so I did a test where I copied my NSManagedObject property by property, only difference is that is is a subclass of just NSObject instead of NSManagedObject. Sadly this behaves in the exact same way. It also leaves values as (null)
Hope someone can pick up on where I go wrong with these string tests :)
Thank You
You could set the default property value of your entity to "N/A" (that's a good practice, because you might want to use sqlite for iPhone app shipping, and it doesn't work well with null values because sqlite and cocoa don't have the same vision of "null") and set "optional" to "No".
if([[f valueForKey:s] isKindOfClass:[NSString class]] && [[f valueForKey:s] isEqualToString:@"NA"]) {
//Tell your program to know that it's null if it needs to know
}
Cheers
What is allPossibleStrings? You could do this to get to all the properties:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntityName" inManagedObjectContext:moc];
for (NSString *attr in [entity attributesByName]) {
[object setValue:@"n/a" forKey:attr];
}
The issue is that when something is nil, what you can get back from any managed object property (not just strings) is an NSNull object. So if you check also for isKindOfClass:[NSNull class]
I think your code will do what you want.
精彩评论