Objective-C error: Property 'active' is a scalar type on class 'Routine'. Cannot generate a getter method for it

不羁的心 提交于 2019-12-05 22:57:11

问题


I'm getting the above error when the following runs in the iphone simulator (3.0 OS):

@interface Routine : NSManagedObject {

}

@property (nonatomic) BOOL active;

@implementation Routine
@dynamic active
@end

As you can see, I'm subclassing NSManagedObject because I'm using Core Data. In my data model, "active" is an option attribute of type Boolean.

What am I doing wrong here?

Thanks!


回答1:


Everything that comes out of CD is an object, not a scaler. So, changer your code to:

@interface Routine : NSManagedObject {

}

@property (nonatomic) NSNumber * active;

@implementation Routine
@dynamic active
@end

If you want you can add a convenience accessor to deal with it as a scalar:

- (BOOL) activeScalar {
  return self.active.boolValue;
}

- (void) setActiveScalar:(BOOL)active_ {
  self.active = [NSNumber numberWithBool:active_];
}

Finally, if you control-click on a property in the model editor it will bring up an enormous contextual menu, including options to copy the appropriate declarations and definitions into your paste board, so you don't have to write them yourself.




回答2:


For what it's worth, I found the docs provide a slightly different solution to scalars. Generally you're discouraged from using scalars instead of objects, but if you do then http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdNSAttributes.html explains how to do it. You use the "primitiveName" and "setPrimitiveName" to access automatically generated accessors that put your scalar into an object (e.g. NSNumber). Then create a scalar @property and write accessors for your property that use the primitives.

This seems expensive in that under the hood CoreData is storing your attribute as a scalar in the peristent store and converting it to an object to expose it as a primitive. So when you implement setName, as I read the docs and sample code, your value is placed in an object and then the scalar is extracted again in the setPrimitiveName automatic implementation. Seems like unnecessary marshaling back and forth for each get or set.



来源:https://stackoverflow.com/questions/1152025/objective-c-error-property-active-is-a-scalar-type-on-class-routine-cannot

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