My managed object has a relationship called items. My subclass has a method called itemCount. Unfortunatly my attempts to get the object count in the items relationship always returns 0. Here’s the relevant code:
@interface List : NSManagedObject {}
@property (nonatomic, retain) NSSet* items;
@property (nonatomic, readonly) NSNumber * itemCount;
@end
@implementation List
@dynamic items;
- (NSNumber *)itemCount
{
NSNumber * tmpValue;
NSSet *items = self.items;
if (items = nil) {
return 0;
}
tmpValue = [NSNumber numberWithInt:[items count]];
return tmpValue;
}
@end
When I walk through the itemCount method it appears to work just fine, but the self.items counts always return zero objects. Any ideas?
First of all, you’re assigning
niltoitemsin yourifstatement. You wantif (items == nil)(orif (!items)). Always use the debugger to step through your code to test your logic when something odd is happening.Second of all, you can get the count with the keypath,
@"@count.items"without the need for your-itemCountmethod. You could also doself.items.count(becausecountis a property of theitemsset asitemsis a property ofself, which is equivalent to[[self items] count]).