1

I have already read up on @synthesize and found some really great information on this question: What exactly does @synthesize do? and I understand the difference between an instance variable and a property, but in the code I inherited, my problem goes a little further than that and I would like to know what it does (or if it's necessary) in the following circumstance. If more code context is needed just ask.

// example.h
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;    

// example.m
@synthesize managedObjectContext = _managedObjectContext;

//... later on in example.m
- (NSManagedObjectContext *)managedObjectContext {        
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    return _managedObjectContext;
}

So in the example from the linked answer MapView and MapView1 were both defined in the .h file whereas in my example, a pointer to _managedObjectContext is never defined as far as I can tell after doing a global search. We're using it with the @synthesize keyword as well as providing a concrete definiton of managedObjectContext in the implementation file.

So my question is really 2:

  1. Is @synthesize even doing anything here?
  2. Why does it still compile when _managedObjectContext isn't defined like in the other example question?
Community
  • 1
  • 1
akousmata
  • 1,005
  • 14
  • 34

2 Answers2

3
  1. No, as you've provided the getter for the property.
  2. Because the property provides a default backing instance variable called _managedObjectContext.

Note: there is no need to @synthesize at all these days.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • So when I declare a property `managedObjectContext`, the compiler automatically creates an ivar called `_managedObjectContext`? So in my example I could simply write the `managedObjectContext` implementation as `return [[NSManagedObjectContext alloc] init];` and the compiler takes care of the rest? Are there any memory leak types of things I should worry about when doing this? – akousmata Apr 15 '16 at 19:00
  • @akousmata Well not quite as your getter is kinda special. I think you should dump it and allocate that object in the `init` method instead. Much more conventional. – trojanfoe Apr 15 '16 at 19:03
  • I'll try to look into that, not sure I can without breaking a bunch of other things. Thanks for the info. Still quite new to iOS – akousmata Apr 15 '16 at 19:09
0

In today's framework you don't need to @synthesize. Property will auto synthesize by the framework.

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75