简体   繁体   中英

NSManagedObject Incompatible pointer type warnings

Let me make sure first I have X-Code 4.3.2 version and iOS 5.1 SDK. I have below methods used in my project for core-data operation. Both method giving same warning. ie "Incompatible pointer types returning 'NSManagedObject *' from a function with result type 'NSManagedObject <Protocol> " .

Method A:

- (NSManagedObject<Protocol> *)newMOforNilMOC 
{
    return [[NSManagedObject alloc] initWithEntity:[self entityDescription] insertIntoManagedObjectContext:nil];
}

For method method A I just do typecasting and added (NSManagedObject<Protocol>*) then warning get removed as stated below.

- (NSManagedObject<Protocol> *)newMOforNilMOC 
{
    return  (NSManagedObject<Protocol> *) [[NSManagedObject alloc] initWithEntity:[self entityDescription] insertIntoManagedObjectContext:nil];
}

Method B:

+ (NSManagedObject<Protocol> *) newInContext:(NSManagedObjectContext *)context 
    {   
        return [[NSEntityDescription insertNewObjectForEntityForName:[[(NSManagedObject<Protocol> *)self class] entityName]                                     inManagedObjectContext:context]retain]; 
    }

For method B when I do typecasting it will not work hence I just change the name of method from newInContext to AddnewInContext (Found somewhere when googled) then warning got removed.

I have following Questions:

  1. If first method is required typecasting then why second one is not working with that solution?
  2. What is the exact meaning of changing the name of method. Is this proper way to remove above warning? Why typecasting not working in method B ?

This could be complicated one but feel free to leave comment if you have any doubt. Because I want to know the difference, at least I get to learn some new thing about core data.

I think you are using 'self' in a class method. You should use the class itself. Let me show by code

+ (NSManagedObject<Protocol> *) newInContext:(NSManagedObjectContext *)context 
{   
        //Usage of [self class] is not correct, as self points already to a class.
        NSEntityDescription* desc = [NSEntityDescription entityForName:@"myObjectName" inManagedObjectContext:context];
        return [[NSEntityDescription insertNewObjectForEntityForName:desc inManagedObjectContext:context]retain]; 
}

You can't cast a class type to a 'id' type, which is the one that self points to if you are inside an object method, not a class method. I don't think any method renaming solves any warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM