开发者

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

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"];
    [se开发者_运维技巧lf 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜