Can't get rid of compiler warnings for primitiveValue accessors in transient property getter impls

余生长醉 提交于 2019-12-07 10:14:04

问题


I've implemented a transient property as below on one of the models in my app. It is declared in the model design as a transient property with undefined type.

@property (nonatomic, readonly) NSNumberFormatter *currencyFmt;

The current (warning-free) impl of this accessor is:

- (NSNumberFormatter *) currencyFmt
{
    [self willAccessValueForKey:@"currencyFmt"];
    NSNumberFormatter *fmt = [self primitiveValueForKey:@"currencyFmt"];
    [self didAccessValueForKey:@"currencyFmt"];

    if (fmt == nil)
    {
        fmt = [[[NSNumberFormatter alloc] init] autorelease];
        [fmt setNumberStyle:NSNumberFormatterCurrencyStyle];
        [fmt setLocale:[self localeObject]];
        [self setPrimitiveValue:fmt forKey:@"currencyFmt"];
    }

    return fmt;
}

The call to primitiveValueForKey: is the problem here, since the documentation specifically warns against using this version of the primitive lookup:

You are strongly encouraged to use the dynamically-generated accessors rather than using this method directly (for example, primitiveName: instead of primitiveValueForKey:@"name"). The dynamic accessors are much more efficient, and allow for compile-time checking.

The problem is that if I try to use primitiveCurrencyFmt instead of primitiveValueForKey:@"currencyFmt", I get a compiler warning saying that the object may not respond to that selector. Everything works fine at runtime if I just ignore this warning, but warnings are horrible and I don't want to commit any code that has them in there.

I tried declaring the property with @dynamic and @synthesize at the top of the file and nothing seems to help. What do I need to do to use the recommended dynamic accessors without generating these warnings?

Any help much appreciated.


回答1:


Declare the methods in a category on your managed object class:

@interface MyManagedObject : NSManagedObject
...
@end

@interface MyManagedObject (PrimitiveAccessors)

- (NSNumberFormatter*)primitiveCurrencyFmt;
- (void)setPrimitiveCurrencyFmt:(NSNumberFormatter*)value;

@end

Apple uses this pattern in several places in the documentation to suppress compiler warnings.




回答2:


With auto-synthesize (new since 2010 when this was asked/answered), you can alternatively declare the properties instead. Less code, eliminate typos, etc.

@interface MyManagedObject (PrimitiveAccessors)

@property (nonatomic) NSNumberFormatter *primitiveCurrencyFmt;

@end

Apple Example.



来源:https://stackoverflow.com/questions/4565279/cant-get-rid-of-compiler-warnings-for-primitivevalue-accessors-in-transient-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!