0
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface Employee : NSManagedObject

@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSNumber* pin;

-(id) initWithName:(NSString*)name Pin:(NSNumber*)pin;

@end


@implementation Employee

@dynamic name;
@dynamic pin;

-(id) initWithName:(NSString*)iname Pin:(NSNumber*)ipin{
    self = [super init];
    if(self){
        name = iname;
        pin = ipin; 
    }
    return self;
}
@end

Compiler says name and pin are undeclared in the .m file. What am I doing wrong? Putting self.name and self.pin works, but could someone tell if this is proper or why this works? etc. Thank you in advance for help.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Byron S
  • 99
  • 2
  • 9
  • Proper way to synthesize a property is: @synthesize pin = _pin; – zambrey Jun 20 '13 at 05:08
  • @zambrey His superclass is `NSManagedObject`. If `name` and `pin` are entity attributes defined in his Core Data model, he should use `@dynamic`, not `@synthesize`. – rob mayoff Jun 20 '13 at 05:09

1 Answers1

4

You wrote this in your initializer:

name = iname;

Since you don't have a local variable named name, the compiler looks for an instance variable named name, or a static or global variable named name. You don't have an instance variable named name, or a static or global either. You have a property named name. To set the property, you need to either use “dot notation”:

self.name = iname;

or you need to send a setName: message:

[self setName:iname];

Both of these compile to exactly the same code.

Note that since your superclass is NSManagedObject, I assume Employee is an entity defined in your Core Data model with attributes name and pin. If so, using @dynamic is correct. If those are not attributes defined in your model, you should probably be using @synthesize (or omitting both @dynamic and @synthesize and letting the compiler auto-synthesize the properties).

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Oh i see. I was under the impression that synthesized properties automatically produced the variable. Must've read something incorrectly in my books. Thank you very much rob. – Byron S Jun 20 '13 at 05:09
  • You're not synthesizing the properties. You're declaring them dynamic. Declaring them dynamic is correct if they are entity attributes defined in your Core Data model. I assume they are entity attributes since your superclass is `NSManagedObject`. – rob mayoff Jun 20 '13 at 05:10
  • 1
    @ByronS: Note that according to the [NSManagedObject documentation](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/Reference/NSManagedObject.html), managed objects must be initialized using the designated initializer (`initWithEntity:insertIntoManagedObjectContext:`). – Martin R Jun 20 '13 at 05:46