Sandeep
Sandeep

Reputation: 21144

Creating a transient relational property

I think this is a simple issue but I have somehow leaked object in core data. I have a simple one to one relation in core data.

       Person           <-------->         Address

        -name                                -city
        -email                               -country

The person model was relatively simple with just few attributes. But, I wanted to add the getter in Person class to access the city and country from the person class itself. So, I did something like,

@interface Person:NSManagedObject
    @property(nonatomic, strong) NSString *name;
    @property(nonatomic, strong) NSString *email;
    @property(nonatomic, strong) Address *address;
    -(NSString*)city;
    -(NSString*)country;
@end


@implementation Person
  -(NSString*)city{
     [self willAccessValueForKey:@"address"];
     NSString *c = [self valueForKeyPath:@"address.city"];
     [self didAccessValueForKey:@"address"];
   }

   -(NSString*)country{
     [self willAccessValueForKey:@"address"];
     NSString *c = [self valueForKeyPath:@"address.country"];
     [self didAccessValueForKey:@"address"];
   }

@end

With these getter I have been able to access the city with just simple getters in Person model as;

    person.city   and  person.country

But, I feel this is not the correct way to do it. How do I implement this feature to ensure that the memory is not leaked.

Upvotes: 0

Views: 119

Answers (3)

Jody Hagins
Jody Hagins

Reputation: 28409

As Ganee says, you can just access

person.address.city

but if you absolutely need the city method, you should use the generated properties:

- (NSString*)city {
    return address.city;
}

though this hides your relationship access so make sure that's what you want.

In regards to your memory leak, you need a really, really, really good reason to not use ARC for new projects.

Upvotes: 1

Analog File
Analog File

Reputation: 5316

You forgot the return statements in the code, but I guess they are there in the actual code you are using.

I do not see any leak in the code itself. Remember however that you are responsible for faulting everything when done as Core Data relationships inherently create retain cycles. See Core Data And Retain Cycles

Upvotes: 1

Ganee....
Ganee....

Reputation: 302

You can not access city or country directly from Person, you can access like....

Person.Address.city
Person.Address.country

and no need of implement the:

-(NSString*)city;
-(NSString*)country;

Upvotes: 1

Related Questions