djay
djay

Reputation: 375

How to save non-english language/special characters in core data?

Language of string coming from server is Herbew and when i show directly that data to my view, the characters come right but next time when i try to fetch it from data base "????" comes instead of right characters!

//THIS IS WHERE I SAVE A CONTACT WITH DISPLAY NAME TO DB//

    -(BOOL)addContact:(ALContact *)userContact {

        ALDBHandler * dbHandler = [ALDBHandler sharedInstance];

        DB_CONTACT* existingContact = [self getContactByKey:@"userId" value:[userContact userId]];
        if (existingContact) {
            return NO;
        }

        BOOL result = NO;

        DB_CONTACT * contact = [NSEntityDescription insertNewObjectForEntityForName:@"DB_CONTACT" inManagedObjectContext:dbHandler.managedObjectContext];
        contact.displayName = userContact.displayName;

        NSError *error = nil;
        result = [dbHandler.managedObjectContext save:&error];

        if (!result) {
            NSLog(@"addContact DB ERROR :%@",error);
        }

        return result;
}

Upvotes: 1

Views: 852

Answers (2)

Tom Harrington
Tom Harrington

Reputation: 70956

It's hard to tell exactly where things are going wrong (we could go round and round via discussion in comments for a long time), but the answer will be something like:

  1. Core Data does not require any special steps to store non-English text. It just works. However...
  2. String encodings are very easy to screw up, and are an extremely common source of errors. Somewhere in your code (maybe in multiple places) you're getting the encoding wrong, which causes bogus strings. It only looks like a Core Data problem because you're using this badly-encoded string with Core Data.

As an experiment I created a new Xcode project using the "Master-Detail Application" template, using Core Data. Then I added a field to the default "Event" entity called "name" and modified the UI to display this string.

Then I assigned your string as the value of "name":

newEvent.name = @"מתןאצ׳אט";

After creating a few instances, quitting and relaunching the app, I can verify that the string was saved correctly, retrieved intact, and displayed in the UI correctly:

iOS Simulator screenshot

So, stop looking at your Core Data code and start looking at every step of how you handle this string.

Upvotes: 2

soan saini
soan saini

Reputation: 260

Rather than saving as String save it as NSdata.

Below code might help you in saving and retrieving it back.

var herbrewStrFromServer = "⌘" //Herbew String
let dataSaveCoreData = NSKeyedArchiver.archivedDataWithRootObject(herbrewStrFromServer) //Converting into Nsdata so as to save in coredata
let actualStringRetreived = NSKeyedUnarchiver.unarchiveObjectWithData(dataSaveCoreData) as! String // retrieving it back from core data

Upvotes: 1

Related Questions