开发者

Problem accessing relationship objects in an NSManagedObject

开发者 https://www.devze.com 2022-12-15 17:48 出处:网络
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 r开发者_开发百科eturns 0

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 r开发者_开发百科eturns 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 nil to items in your if statement. You want if (items == nil) (or if (!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 -itemCount method. You could also do self.items.count (because count is a property of the items set as items is a property of self, which is equivalent to [[self items] count]).

0

精彩评论

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