0

我正在尝试覆盖 an 的设置器,NSManagedObject以便我可以传入不同类型的对象,进行转换,然后设置属性。像这样的东西:

- (void)setContentData:(NSData *)contentData
{
    NSString *base64String;
    // do some stuff to convert data to base64-encoded string
    // ...
    [self willChangeValueForKey:@"contentData"];
    [self setPrimitiveValue:base64String forKey:@"contentData"];
    [self didChangeValueForKey:@"contentData"];
}

因此,在这种情况下contentData, my 的字段NSManagedObject是 an NSString *,我想让 setter 接受 anNSData *然后我将其转换为 anNSString *并将其保存到模型中。但是,如果我尝试这样做,我会从编译器收到有关尝试将 an 分配给 an 的NSData *警告NSString *

myObject.contentData = someNSData;

-> Incompatible pointer types assigning to 'NSString *' from 'NSData *__strong'

有没有更好的方法来解决这个问题,或者我应该完全避免设置器并创建自定义“设置器”,允许我在没有编译器警告的情况下传入NSData *和设置字段?NSString *

4

2 回答 2

3

我认为这是一个例子,你与工具和框架的斗争是一种重要的设计气味。不要试图为您的类覆盖基本属性的预期数据类型。

You didn't say whether the NSManagedObject you are subclassing is under your control. If it's going to be part of your design to have it be something of a template for management of other types of contentData than NSString, then declare it as type id in the root class and specialize in the subclasses. That should prevent the warning.

Probably, you want to follow a Cocoaism: don't subclass. Can you achieve whatever functionality you're looking for from the superclass by say extracting it into a helper class that is held as a property by each of the varying-behavior managed object classes?

于 2012-07-05T18:56:19.587 回答
1

跟进我的“ setContentData: (id) contentData”评论,尝试这样的事情:

- (void)setContentData:(id)thingToWorkWith
{
    NSString * base64String = nil;

    if(thingToWorkWith isKindOfClass: [NSData class])
    {
       // convert data to string   
    }


    if(thingToWorkWith isKindOfClass: [NSString class])
    {
        // set up base64 string properly
    }

    if(base64String)
    {
        // do some stuff to convert data to base64-encoded string
        // ...
        [self willChangeValueForKey:@"contentData"];
        [self setPrimitiveValue:base64String forKey:@"contentData"];
        [self didChangeValueForKey:@"contentData"];
    }
}

确保去掉@synthesize.m 文件中 contentData 的 " " 位,同时创建一个 "getter" 方法,并且因为你使用 " id" 作为 setter 参数,你可能需要调整你的 " @property" 声明少量。我还没有完全尝试过您正在尝试做的事情(即对这种技术不做任何保证)。

于 2012-07-05T18:25:18.513 回答