user3804063
user3804063

Reputation: 849

Objective -C category issue

I have two NSManagedObject subclasses.
I am adding a category method to NSManagedObject for JSON representation, so I have this category named NSManagedObject+JSON.

Implement the category method in NSManagedObject+JSON.m:

- (NSDictionary *)JSONToCreateObjectOnServer {
@throw [NSException exceptionWithName:@"JSONStringToCreateObjectOnServer Not Overridden" reason:@"Must override JSONStringToCreateObjectOnServer on NSManagedObject class" userInfo:nil];
return nil;
}

I am following Ray Weinderleich tutorial for this: http://www.raywenderlich.com/17927/how-to-synchronize-core-data-with-a-web-service-part-2

It states: The issue here is that there is no generic implementation possible for this method. ALL of the NSManagedObject subclasses must implement this method themselves by overriding it.

Whenever a NSManagedObject subclass does NOT implement this method an exception will be thrown.

MY QUESTION HERE IS: I have added the method in category to my subclass. But my code does not call to the method in my NSManagedObject subclasses rather comes to category and throws an exception.

What is missing here? Can anybody point out the reason behind it?

EDIT 1:

- (NSDictionary *)JSONToCreateObjectOnServer {
NSDictionary *date = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"Date", @"__type",
                      [[SDSyncEngine sharedEngine] dateStringForAPIUsingDate:self.date], @"iso" , nil];

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                self.name, @"name",
                                self.details, @"details",
                                self.wikipediaLink, @"wikipediaLink",
                                date, @"date", nil];    
return jsonDictionary;

}

This is the method which I added to my NSManagedObject class.

I have copy and pasted it. Is it becoz of that or I have to follow another procedure to add method to NSManagedObject class.

Upvotes: 0

Views: 114

Answers (1)

Huy Le
Huy Le

Reputation: 2513

Category is created for expanding, not for overriding or modifying. So we cannot assure whether it override or be overridded.

In your case, instead of use Category, you should create a parent class which subclass NSManagedObject. Then put below method to parent class.

- (NSDictionary *)JSONToCreateObjectOnServer {
   @throw [NSException exceptionWithName:@"JSONStringToCreateObjectOnServer Not Overridden" reason:@"Must override JSONStringToCreateObjectOnServer on NSManagedObject class" userInfo:nil];
   return nil;
}

Another class will subclass your parent class instead of NSManagedObject.

P/S: Instead of throw, you should use NSAssert.

References:

Upvotes: 2

Related Questions