Reputation: 265
I have a problem storing ä, ö, ü, ß characters inside CoreData database, and later on reading them in correct form and displaying in UILabel
as text. I am storing as NSString
for example "äüß", but I am getting strange characters as result of reading from database. Any idea how to read correct value of NSString
property?
UPDATE:
Storing to CoreData
Database:
OCDatabaseFloor *floor = (OCDatabaseFloor*) [NSEntityDescription insertNewObjectForEntityForName:FLOOR_ENTITY_NAME inManagedObjectContext:managedObjectContext];
[floor setFloorName:floorName];
[self saveContext];
Save context function is saving changes to database.
Retrieving from database floor object:
NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:FLOOR_ENTITY_NAME inManagedObjectContext:managedObjectContext];
[fetch setEntity:entity];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"floorID == %d",[floorID intValue]];
[fetch setPredicate:pred];
NSArray *floors = [managedObjectContext executeFetchRequest:fetch error:nil];
return [floors objectAtIndex:0];
And class OCDatabaseFloor:
@interface OCDatabaseFloor : NSManagedObject
@property (nonatomic, retain) NSNumber * floorID;
@property (nonatomic, retain) NSString * floorName;
@end
Upvotes: 2
Views: 583
Reputation: 70956
Core Data on its own does not have any problem with those characters. As a test I created a demo project with one entity named Entity
that has one attribute, a string called name
. Then I ran this code:
NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:self.managedObjectContext];
[obj setValue:@"äüß" forKey:@"name"];
NSError *saveError = nil;
if (![self.managedObjectContext save:&saveError]) {
NSLog(@"Save error: %@", saveError);
} else {
[self.managedObjectContext reset];
NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
NSError *fetchError = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:fr error:&fetchError];
if (results == nil) {
NSLog(@"Fetch error: %@", fetchError);
} else {
for (NSManagedObject *obj in results) {
NSLog(@"Name: %@", [obj valueForKey:@"name"]);
}
}
}
The results are:
2015-02-27 10:31:03.759 Junk[4808:25603285] Name: äüß
So, your string is getting corrupted, but it must be happening either before you save it to Core Data or after you read it back.
It looks like you're mixing up character encoding somewhere. You mention that "ö" gets corrupted as "ö". In UTF-8, "ö" is represented as 0xC3B6. In UTF-16, "Ã" is 0xC3 and "¶" is 0xB6. So at some point you're mixing up UTF-8 with UTF-16, but it's not happening because of Core Data.
Upvotes: 2