Tuesday, January 31, 2017

CoreData Entity Attributes Type Checking before Data insertion

We all know that below are the different Attribute types we can use while adding Attributes for a core data Entity.

  • Undefined
  • Integer 16
  • Integer 32
  • Integer 64
  • Decimal
  • Double
  • Float
  • String
  • Boolean
  • Date
  • Binary Data
  • Transformable

Incase we need to add records to any core data entity from service response, We need to properly check the attribute type and based on the type we need to parse the service response values and store.

We can take all attributes into a dictionary as shown below.


  
    NSEntityDescription *entity = [self entity];
    NSDictionary *attributesDictionary = [entity attributesByName];


Let’s say we have response from the service and we have taken that into a Dictionary.


  
      NSDictionary *dataDictionary;


Now, instead of directly pushing the data into core data, we need to check the attribute type and the respective data type.

Let’s say we have a Date attribute type. Usually we get date as string(“28-06-1986”) from service response. So we need to check the response value type and convert it into a NSDate object and store.


     
 for (NSString *attribute in attributesDictionary) {

     id responseVal = [dataDictionary objectForKey:attribute];
     NSAttributeType attributeType = [[attributesDictionary objectForKey:attribute] 
                                                                                             attributeType];

     if ((attributeType == NSDateAttributeType) && ([responseVal isKindOfClass:[NSString 
                                                                                                            class]])) {
            responseVal = [dateFormatter dateFromString:value];
     }

 }


Like that we need to check each and individual attribute and store.


Hope this post is useful. Feel free to comment incase of any queries.


No comments:

Post a Comment