How to “break” when a value of core data change?

风流意气都作罢 提交于 2020-01-06 03:06:26

问题


I have this bug where the value of anImage.URL suddenly become nil. anImage is an object of class Image. There are 5 such values in an array. Somehow at least one of them have their URL turn into nil somehow.

I have no idea where that thing is changed.

So I set this up as categories for anImage.URL = something

-(void) setURL:(NSString *)URL
{

    [super setValue:URL forKey:NSStringFromSelector(@selector(URL))];
}

And set breakpoint there.

However, it becomes a problem because it simply recursively call itself.

What should I do?

The debugger break when value change don't really work. After all it's an array. What should I set to watch anyway?

I am not sure how to use keyValueObserving.

Basically I want to reimplement -(void) setURL:(NSString *)URL to work exactly like before. The only difference is I want to put a breakpoint there.


回答1:


You can implement a custom setter method for debugging or setting a breakpoint.

An example can be found in Custom Attribute and To-One Relationship Accessor Methods in the "Core Data Programming Guide".

You create a category (e.g. "MyAccessors") on the managed object subclass "Image" (if you don't have one already). In the implementation file "Image+MyAccessors.m" you add

@interface Image (PrimitiveAccessors)
- (void) setPrimitiveURL:(NSString *)newURL;
@end

@implementation Image (MyAccessors)

- (void)setURL:(NSString *)newURL
{
    [self willChangeValueForKey:@"URL"];
    [self setPrimitiveURL:newURL];
    [self didChangeValueForKey:@"URL"];
}

@end

The "trick" is (and it took me some time to figure this out), that you have to declare the primitive accessor in a different category, not in the category where you implement the custom accessor methods.

Alternatively, you can implement the custom accessor like this:

- (void)setURL:(NSString *)newURL
{
    [self willChangeValueForKey:@"URL"];
    [self setPrimitiveValue:newURL forKey:@"URL"];
    [self didChangeValueForKey:@"URL"];
}

In this case you don't have to declare the primitive accessor method.




回答2:


This is not the straight answer to the question. The question is how to debug this.

Well, I found the bug. When NSManagedObject behave erratically make sure you check that you do not use managedObject context across threads. Technically you can with perform block, but that's a different story.

I just want to share this. I'll try Martin' solution latter.



来源:https://stackoverflow.com/questions/13404111/how-to-break-when-a-value-of-core-data-change

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