3

当我尝试设置我的变量eventId时,我NSManagedObject (Event)得到了错误EXC_BAD_ACCESS。我不知道原因。

这是我班级的代码Event

@interface Event : NSManagedObject 

@property (assign)              NSInteger   eventId;

@end


@interface Event (PrimitiveAccessors)
- (NSInteger)primitiveEventId;
- (void)setPrimitiveEventId:(NSInteger)event_id;
@end



@implementation Event
@dynamic eventId;

...

-(NSInteger)eventId
{
    [self willAccessValueForKey:@"eventId"];
    NSInteger id = [self eventId];
    [self didAccessValueForKey:@"eventId"];
    return id;
}

-(void)setEventId:(NSInteger)event_id
{
    [self willChangeValueForKey:@"eventId"];
    [self setPrimitiveEventId:event_id]; //Here I get the error
    [self didChangeValueForKey:@"eventId"];
}

...

任何人都可以解决问题?

感谢帮助

4

2 回答 2

4

如果您仔细查看文档,您会发现示例中标量属性的原始访问器方法double length仍然使用NSNumber *参数和返回值:

@interface MyManagedObject (PrimitiveAccessors)
@property (nonatomic, retain) NSNumber *primitiveLength;
@end

[注意:我添加了*Apple 文档中原始代码片段中缺少的内容。]

所以尝试用NSNumber *参数和返回值声明你的原始访问器。

或者如果你真的必须,考虑实现你自己的原始访问器方法

于 2012-07-09T22:16:14.710 回答
0

解决方案:

@interface Event (PrimitiveAccessors)
- (NSNumber *)primitiveEventId;
- (void)setPrimitiveEventId:(NSNumber*)event_id;
@end

-(NSInteger)eventId
{
    [self willAccessValueForKey:@"eventId"];
    NSNumber *id = [self primitiveEventId];
    [self didAccessValueForKey:@"eventId"];
    return [id integerValue];
}

-(void)setEventId:(NSInteger)event_id
{
    [self willChangeValueForKey:@"eventId"];
    [self setPrimitiveEventId:[NSNumber numberWithInteger:event_id]];
    [self didChangeValueForKey:@"eventId"];
}
于 2012-07-09T22:25:20.043 回答