Question

I am trying to create a setter/getter for a property on ARC.

I have this:

@property (strong, atomic) MyMytableArrayClass *myArray;

-(MyMytableArrayClass*) myArray {
  @synchronized(self) {
    if (_myArray == nil) { //*
      _myArray = [[MyMytableArrayClass alloc] init]; //*
      _myArray.flag = YES; //*
      }
    return _myArray; //*
  }
}

-(void) setMyArray:(MyMytableArrayClass*)anArray {
  @synchronized(self) {
    _myArray = anArray; //*
  }
}

I have errors on the lines marked with //* with this error use of undeclared identifier _myArray why?

Était-ce utile?

La solution

The compiler only automatically synthesizes the instance variable for a property if it has to synthesize at least one accessor method.

If you implement both setter and getter method for your property (or if you implement the getter for a read-only property), the instance variable is not synthesized automatically.

In this case you have to add

@synthesize myArray = _myArray;

explicitly if you need the instance variable. Alternatively, you can declare _myArray as an ivar in the class extension.

Autres conseils

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html

The compiler will automatically synthesize an instance variable in all situations where it’s also synthesizing at least one accessor method. If you implement both a getter and a setter for a readwrite property, or a getter for a readonly property, the compiler will assume that you are taking control over the property implementation and won’t synthesize an instance variable automatically.

If you still need an instance variable, you’ll need to request that one be synthesized:

@synthesize property = _property;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top