0

In have an NSManagedObject subclass:

    @interface ManagedActivityAmount : NSManagedObject

    @property (nonatomic, retain) NSNumber * distance;
    @property (nonatomic, retain) NSNumber * duration;
    @property (nonatomic, retain) NSSet *sets;

    @end

    @interface ManagedActivityAmount (CoreDataGeneratedAccessors)

    - (void)addSetsObject:(ManagedPowerSet *)value;
    - (void)removeSetsObject:(ManagedPowerSet *)value;
    - (void)addSets:(NSSet *)values;
    - (void)removeSets:(NSSet *)values;

    @end

I encounter a problem in keeping a reference to an object that i added to the sets relationship using the:

    - (void)addSetsObject:(ManagedPowerSet *)value;

the ManagedPowerSet object was successfully added to the ManagedActivityAmount sets property, and I'm assuming it's retain count is 1 due to this (the actual object was autoreleased before that so the retain count was 0 before adding it to the set). am I correct? am I missing something?

I'm assigning the ManagedPowerObject to another instance variable of the view controller (this is a private instance variable, not a retained property) but I can't seem to access it later. should I retain it? i'm just about to do so and check, but I really want to understand we it wasn't retained in the first place.

thanks :)

4

2 回答 2

0

If you are not using ARC, you must claim ownership (retain) of anything you intend to use at a later time. And release it when you are done with it (for ivars this would generally be in the class's dealloc implementation). I suggest you use properties to do this as it generally results in less coding. This is due to the fact that you must always release old pointers before assigning new ones:

[_managedPowerObject release];
_managedPowerObject = [managedPO retain];

This would be used whenever assigning to an ivar (instance variable) directly. Or you could just use a property:

@property (nonatomic, retain) ManagedPowerObject *managedPowerObject;

The default implementation of the property will handle the release/retain for you and now you can simply use:

self.managedPowerObject = managedPO;

I would suggest reading through Apple's memory management guidelines: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html#//apple_ref/doc/uid/10000011-SW1

于 2012-06-05T15:23:48.883 回答
0

So i wasn't missing anything, the retain count assumptions were correct, no retain was needed since the object outlives the controller, if it were a property it should have been assigned..

the problem was really stupid on my part, i didn't allocate something else that made it looked like the object was lost, though actually it wasn't.

as for the debugger and what seems as if the two pointers that were supposed to point to the same address but weren't - i have no clue why this happens, i guess the xcode debugger has some delays..

于 2012-06-05T15:43:51.540 回答