Can't set the attribute "trainable_weights" likely because it conflicts with an existing read-only #property - tf.keras

when i define my own layers with tf.keras,like this:
def build(self, input_shape):
self.input_spec = [InputSpec(shape=input_shape)]
shape = (input_shape[self.axis],)
#print('shape:',type(shape))
init_gamma = self.scale * np.ones(shape)
self.gamma = tf.Variable(init_gamma,name='{}_gamma'.format(self.name))
print('type',type([self.gamma]))
self.trainable_weights=[self.gamma]
It raise a bug in the tf/python/keras/base_layer.py that I can't set the attribute "trainable_weights" likely because it conflicts with:
an existing read-only #property of the object. Please choose a different name
What should I do?

Related

#class #synthesize useablility

Ok, I have class, that I create for my Core Data
LoginPass.h
Then I have First class
FirstClass.h
And then I need use this classes in SecondClass, where I declare them with #class. Heder file
SecondClass.h
...
#class FirstClass;
#class LoginPass;
...
#interface SecondClass : UIViewController
{
......
}
#property (strong, nonatomic) FirstClass *fromFirstClass;
#property (strong, nonatomic) LoginPass *myEntity;
...
#end
And in .m file
#import "SecondClass.h"
#import "FirstClass.h"
#import "LoginPass.h"
#implementation SecondClass
...
#synthesize fromFirstClass = _fromFirstClass;
#synthesize myEntity = _myEntity;
...
Ok, I can make some mistakes in code, sry for it.
I really don't know and now don't interesting why I need write
#synthesize myEntity = _myEntity;
but not
#synthesize myEntity;
But I have another question. Why I can use then in my code
self.fromFirstClass
But I cann't use
self.myEntity
Xcode give me an error and say me that I should use
self._myEntity
What the difference? Why I can use self.fromFirstClass but not self.myEntity?
#end
You are confusing instance variables which are variables parts of an object structure, and properties which are really methods to set and get a value.
When you declare #property (strong, nonatomic) FirstClass *fromFirstClass; you actually declare two methods - (FirstClass *)fromFirstClass and - (void)setFromFirstClass:(FirstClass *)aFirstClass.
When you use the dot syntax FirstClass *classA = self.fromFirstClass;, you actually call a method, it is equivalent to FirstClass *classA = [self fromFirstClass];. In the same way, if you write self.fromFirstClass = classB;, you actually call: [self setFromFirstClass:classB];.
If you use the name of an instance variable directly inside an object method, you access this variable.
Now, when you write #synthesize fromFirstClass; in the modern runtime, you let the compiler create a instance variable with the same name fromFirstClass and write the two methods - (FirstClass *)fromFirstClass and - (void)setFromFirstClass:(FirstClass *)aFirstClass that will get and set the instance variable.
If you write #synthesize fromFirstClass = _fromFirstClass;, the same thing happens, except the name of the instance variable which is created has an underscore in front of it.
Finally, in the more recent versions of the compiler, if you don't write anything, the default behavior is to #synthesize fromFirstClass = _fromFirstClass automatically for you.
#synthesize fromFirstClass = _fromFirstClass;
#synthesize myEntity = _myEntity;
These above lines are correct but nowadays you are not required to synthesize.#synthesize is put by compiler itself.
When you use self.prop you mean you are accessing property.
When you use _prop you call property directly.
EDIT:
When you use self.prop you call the method depending on lhs or rhs of =(assignment) :
-(NSString *)prop; //gets called when you use myName=self.prop;
and/or
-(void)setProp; //gets called when you use self.prop=#"master";
On the other side, if you try to use self._myEntity then it will look for method name having _ which is not there, resulting in Error.
The compiler would add
#synthesize myEntity = _myEntity;
if you omit the #synthesize totally.
However, you could use as well
#synthesize myEntity;
The key difference is that in the first case, your local variable is called _myEntity while the getter is myEntity and the setter is setMyEntity. So from external you would access yourObject.myEntity either for setting or getting the value. The compiler will take care, that the setter and getter is called. You do not access the prperty directly.
[yourObject.myEntity = value] ist identical to [yourObject setMyEntity:value] as well as value = yourObject.myEntity is identical to value = [yourObject myEntity].
So far from accessing properties or their getter and setter from outside. From inside your class you may think that self.myEntity = value is identical to myEntity = value (for the second case). But it is NOT. self.myEntity calls the setter (or getter). This is important especially for the getter becaus that comes with important memory management for free - with or without ARC. While myEntity = value directly accesses the property.
And here comes the _ and its key advantage (imho). If you use the _ notation then the property is called _myValue. Doing so it is explicitely clear for you and the readers of your code when the actual property is accessed directly and when the getter and setter are used.

concepts of properties with corresponding ivars

i have a general question about properties and ivars.
ive seen many different examples to use properties and it confuses me a bit.
method 1 only using a property without a corresponding ivar.
#property (...) Type *name;
#synthesize name;
method 2 using a property and an ivar
#interface{
Type *ivarName;
}
#property (...) Type *name;
#synthesize name = ivarName;
method 3 ignoring properties and working with ivars
#interface{
Type *ivarName;
}
ivar = ...;
i currently use method 1 for most things i do, it just works. but i have startet to wonder if i might be missing something here. i have read a lot of questions about ivars VS properties, but none of them seemed to really care about how they work together.
in most sample projects i've seen method 2 is used. so my question is: is there any advantage in defining a property and an ivar, and then assign the property to the ivar, than just having a property?
is the solution as simple as: only with a property can an ivar be set from 'outside'?
i have read: Must every ivar be a property? and Property vs. ivar in times of ARC but was not able to draw a final conclusion.
is the solution as simple as: only with a property can an ivar be set from 'outside'?
Essentially, yes. Ivars in Obj-C are (by default) "protected", meaning that the compiler won't allow you to access them externally to the object's own code. For example, given the following class declaration:
#interface Dunstable : NSObject
{
NSString * crunk;
}
#end
You might think you'd be able to access the ivar after creating the object, but trying results in an error:
Dunstable * d = [[Dunstable alloc] init];
d->crunk = #"Forsooth"; // Error: "Instance variable 'crunk' is protected
That's why ObjC uses accessor methods. Defining them manually was mandatory before the advent of declared properties:
#implementation Dunstable
- (NSString *)crunk {
return crunk; // implicit ivar access, i.e. self->crunk
}
- (void)setCrunk: (NSString *)newCrunk {
[newCrunk retain];
[crunk release];
crunk = newCrunk;
}
#end
Now, using the #property and #synthesize directives creates those accessor methods for you (as well as the variable itself). (The manual memory management in the setter is of course also obsolete under ARC.)
It is possible to make an ivar that's accessible from outside the object:
#interface Dunstable : NSObject
{
#public
NSNumber * nonce;
}
#end
Dunstable * d = [[Dunstable alloc] init];
d->nonce = [NSNumber numberWithInt:2]; // Works fine
but this isn't considered good Objective-C style.
The Objective-C Programming Language doc contains a "Historical Note" about this:
Note: Historically, the interface required declarations of a class’s instance variables, the data structures that are part of each instance of the class. These were declared in braces after the #interface declaration and before method declarations:
[...]
Instance variables represent an implementation detail, and should typically not be accessed outside of the class itself. Moreover, you can declare them in the implementation block or synthesize them using declared properties. Typically you should not, therefore, declare instance variables in the public interface and so you should omit the braces.
This is a pretty big change (I was actually surprised that there's no syntax given for ivars declared in #interface anymore in that doc), but it's definitely for the better. You should use declared properties; they do the right thing and make your code cleaner and safer.
When you write:
#synthesize name;
an ivar name is created, and it has the same name as the property. So you can access it with or without self.
In reality if you write
self.name = #"hello";
you are accessing the property, and if you write
name = #"hello";
you are accessing the ivar. Most people (including me) will advise you not to access your ivars directly unless it is really what you want: for example, if you are creating a custom setter or getter for the property. Otherwise always access the property with self.
In my case I always do:
#synthesize name = _name;
The advantage of this approach is that when you forget to write self instead of accessing the ivar you will get an error telling you that the ivar name doesn't exist.
You should never access ivars directly from outside of a class. That's the main function of properties--defining accessor methods for use by other objects. However, it's also good practice to use your accessors from within the same class--this way you can ensure that any appropriate side effects take place (memory management is an obvious example, if you aren't using ARC).
So, Method 3 is usually wrong. Method 1 is roughly equivalent to Method 2--that is, behind the scenes, the runtime is basically creating an ivar for you. Note also that you can set the name of that ivar even if you didn't explicitly define it:
#interface{
//No ivar here!
}
#property (...) Type *name;
#synthesize name = ivarName;
From the second link you supplied, Property vs. ivar in times of ARC, the comment by Denis Mikhaylov on the accepted answer is very telling. He points out that with your case 3, that you can access the iVar through:
classInstance->iVar = #"New value"
But this is considered bad practice. So i'd restate your point as:
Only with a property should an ivar be set from 'outside'

Is there a way to set variables for NSObjects without creating properties for each?

Basically, I have a custom NSObject with a lot of boolean variables. I would like to know if there is a way to modify these variables (from outside this class) without creating a property for each one. Is this possible? Thanks in advance!
Here is part of my object's header:
#interface Polygons : NSObject {
//BOOL values for attributes
BOOL parallelogram;
BOOL rhombus;
BOOL square;
...
}
Use a bitmask to represent a set of related boolean properties. First, define an enum like so:
enum GeometryFlags {
Parallelogram = 1 << 0,
Rhombus = 1 << 1,
Square = 1 << 2,
// etc.
};
You can optionally provide a corresponding typedef statement:
typedef NSUInteger GeometryFlags;
Then you can define a property to allow outside callers to access the bitmask:
// In .h file:
#property (nonatomic) GeometryFlags geometryFlags;
// In .m file:
#synthesize geometryFlags = _geometryFlags;
Calling code can then access the property to get or set the bitfield. Note that you can use the bitwise OR operator to specify multiple values:
// Uses the property accessor to modify two values in the bitmask.
someObj.geometryFlags = Parallelogram | Rhombus;
EDIT
For more info on how to work with a bitmask, see the following:
How do those bitmasks actually work?
http://en.wikipedia.org/wiki/Mask_(computing)
http://en.wikipedia.org/wiki/Bitwise_operation
It's possible with KVC, e.g.:
BOOL isParallelogram = [[myPolygon valueForKey:#"parallelogram"] boolValue];
(see Accessor Search Implementation Details in the Key-Value Coding Programming Guide)
That said, I wouldn't recommend this approach. Not only is it inefficient, but it also breaks encapsulation. This is exactly what properties are made for and there's no reason not to use them in this case.
Cant you just create a method which takes the name of the variable and the value and then assigns it to it?
You can declare them #public:
#interface Polygons : NSObject {
#public
//BOOL values for attributes
BOOL parallelogram;
BOOL rhombus;
BOOL square;
...
and then access them like this:
mypolygon->square = NO;
However, this breaks encapsulation, as #omz explained.
You could write a simple script that generates the properties for you. Here's a starting point:
grep "BOOL [a-zA-Z0-9_]+;$" Polygons.h

Need some help understanding transient properties in Core Data

I read the documentation on transient properties but I can't really understand their purpose. Can someone tell me the difference between having and not having a transient property if I have a custom subclass of NSManagedObject like this?
#interface Board : NSManagedObject
{
NSMutableArray *_grid;
}
// Core Data to-many relationship
#property (nonatomic, retain) NSSet *pieces;
#property (nonatomic, readonly) NSArray *grid;
-(void)awake;
-(void)movePiece:(PieceState *)piece to_x:(int)x y:(int)y;
#end
#implementation Board
#dynamic pieces;
-(void)awakeFromInsert {
[super awakeFromInsert];
[self awake];
}
-(void)awakeFromFetch {
[super awakeFromFetch];
[self awake];
}
-(void)awake {
_grid = nil; // probably not necessary
}
-(NSArray *)grid {
if (!_grid) {
_grid = [[NSMutableArray alloc] initWithCapacity:10];
for (int i = 0; i < 10; i++) {
NSMutableArray *column = [[NSMutableArray alloc] initWithCapacity:10];
[_grid addObject:column];
for (int j = 0; j < 10; j++)
[column addObject:[NSNull null]];
[column release];
}
for (PieceState *piece in self.pieces)
if (piece.x >= 0 && piece.y >= 0)
[[_grid objectAtIndex:piece.x] replaceObjectAtIndex:piece.y withObject:piece];
}
return _grid;
}
-(void)movePiece:(PieceState *)piece to_x:(int)x y:(int)y {
if (x >= 0 && y >= 0) {
NSObject *capturedPieceObject = [[self.grid objectAtIndex:x] objectAtIndex:y];
if ([capturedPieceObject isKindOfClass:[PieceState class]]) {
PieceState *capturedPiece = (PieceState *)capturedPieceObject;
[self removePiecesObject:capturedPiece];
[[self managedObjectContext] deleteObject:capturedPiece];
capturedPiece = nil;
}
}
if (_grid) {
if (piece.x >= 0 && piece.y >= 0)
[[_grid objectAtIndex:piece.x] replaceObjectAtIndex:piece.y withObject:[NSNull null]];
if (x >= 0 && y >= 0)
[[_grid objectAtIndex:x] replaceObjectAtIndex:y withObject:piece];
}
[piece setX:x];
[piece setY:y];
}
- (void)didTurnIntoFault {
[_grid release];
_grid = nil;
[super didTurnIntoFault];
}
#end
So pieces and grid present two ways to access the same data. pieces is the actual Core Data relationship property, and is a dense list of all the pieces. grid is a way to find the contents of a particular space on the board addressed by (x, y) coordinates. grid is built lazily and updated (as long as it exists) when a piece changes location.
I'm not declaring grid as a transient property and everything is working fine. I'm just wondering if there is some unusual condition that could arise that would cause a bug if I don't declare a transient property.
I think I read transient properties are needed to get proper undo behavior if you're doing a derived property like this. I'm not using undo, and in any case I don't see how it could work in this case. If a piece move is undone, the undo manager can assign the old value of _grid back to it (maybe assuming I didn't make it readonly), but the old value is the same as the new value. It is a pointer to the same NSMutableArray instance, only the contents have changed. Anyway I don't use undo.
So do I get any benefit if I declare grid to be a transient property?
Additional question. What if I have code like this:
Board *board = someOtherManagedObject.board;
NSObject *boardContents = [[board.grid objectAtIndex:5] objectAtIndex:5];
Is it possible board is a fault after accessing someOtherManagedObject.board? I'm having trouble understanding faulting too. I think in that case my code would crash. I noticed awake sets _grid to nil. I think the sequence would be like this:
grid getter called
_grid allocated
self.pieces accessed
fault fires
awake called
_grid = nil
return to grid getter
[[_grid objectAtIndex:... access nil value, crash or at least no-op
grid getter returns nil
crash or incorrect behavior when boardContents is expected to contain a value
On the other hand, maybe if I declare grid to be a transient property, then the fault fires before my grid getter is called?
From TechZen:
Faults are placeholder objects that define an object graph with relationships but don't load attribute values. They will log as instances of either an NSManagedObject or of a private _NSFault... class.
Because unmodeled properties are only attributes of the custom NSManagedObject subclass and not the entity, the fault objects know nothing about them. Fault objects are initialized from the data model so that all the keys they respond to must be in the data model. This means faults will not reliably respond to request for unmodeled properties.
Wait what? I'm starting to realize my objects can be faults at any time but are you telling me they might not even be instances of my class!? Or if you use a custom subclass are they guaranteed to be the sort of faults that are instances of NSManagedObject (specifically my subclass)?
If they aren't instances of the custom class then what happens with something like this:
#interface Foo : NSManagedObject {
int data;
}
#property (nonatomic, retain) NSString *modeledProperty;
-(void)doSomething;
#end
#implementation Foo
#dynamic modeledProperty;
-(void)doSomething {
data++;
}
#end
What happens if I call doSomething on a fault?
Doesn't respond to selector, crash
Runs my code, but my instance variables don't exist, who knows what happens when it does data++
data exists, just modeledProperty doesn't exist because it's a fault
Transient properties fix this problem. The transient property provides a key that the context can observe without saving. If you have a fault, sending it a key-value message for a transient property will trigger the context to "fire" the fault and load the complete managed object.
Okay, but what if I have an instance method that's not a property accessor, like doSomething above? How do I make sure I have a real object before I call it? Or can I call it, and first thing in the method body make sure I have a real object (for example by accessing a modeled property)?
In your case, you want to use a transient property for grid if the value of grid depends on the values of any modeled properties of the Board class. That is the only way to guarantee that grid will always be populated when you access it.
I thought if it depended on the values of modeled properties, then it would fire the fault when it depended on them, i.e. the line for (PieceState *piece in self.pieces) fires the fault because it accesses self.pieces, which is a modeled property. But you are telling me which?
I can't even call the grid getter method on a fault
I can call it but I can't use _grid the way I want to
It seems if I understand what you're saying and it's true, the custom subclasses of NSManagedObject are very limited.
They can't have any instance methods that aren't modeled property getters or setters, because the object can't be guaranteed to exist in a useable state when they are called. (Exception: instance methods that are just helper methods for property accessors would be fine.)
They can't have any instance variables for any useful purpose other than temporary caches of computed values, because those instance variables could be erased at any moment. I know they won't be persisted on disk, but I thought they would at least be persisted as long as I retained the object in memory.
If that's the case then are you not intended to put application logic in your custom NSManagedObject subclasses? Should application logic reside in other classes that have references to the managed objects, and the managed objects are only dumb objects that you read from and write to (just a little bit smart, with some capabilities to maintain data consistency)? Is the only point of subclassing NSManagedObject to do some "tricks" with non-standard data types?
The advantage of transient properties comes from the difference between modeled/observed properties and unmodeled/unobserved properties.
The managed object context uses key-value observing (KVO) to monitor modeled properties. Based on the information provided in the data model, it knows what properties must have values, what default, minimum and max values are, when the property is changed and, most importantly, whether the managed object has a key name for a property. All this provides the "managed" part of managed objects.
Modeled properties do not require a custom NSManagedObject subclass but can use a generic NSManagedObject instance initialized to an entity. Accessing a modeled property of a fault (see below) causes the fault to load fully.
The managed object context doesn't observe unmodeled properties and unmodeled properties require a custom NSManagedObject subclass. The unmodeled properties are attributes of the class only and do not show up in the entity and they are never persisted in Core Data. Changes to unmodeled properties go unnoticed by the context.
Faults are placeholder objects that define an object graph with relationships but don't load attribute values. You can think of them as "ghost" objects. They will log as instances of either an NSManagedObject or of a private _NSFault... class. If it is a NSManagedObject the attributes are all empty. When a fault "fires" or is "faulted in" the placeholder object is replaced with a fully populated NSManagedObject instance whose attributes can be read.
Because unmodeled properties are only attributes of the custom NSManagedObject subclass and not the entity, the fault objects know nothing about them. Fault objects are initialized from the data model so that all the keys they respond to must be in the data model. This means faults will not reliably respond to request for unmodeled properties.
Transient properties fix this problem. The transient property provides a key that the context can observe without saving. If you have a fault, sending it a key-value message for a transient property will trigger the context to "fire" the fault and load the complete managed object.
It is important to note that although the data model has a key name for a transient property, the property only has a value when the managed object is fully instantiated and loaded. This means that when you do any fetches, which operate solely in the persistent store, the transient properties will have no values.
In your case, you want to use a transient property for grid if the value of grid depends on the values of any modeled properties of the Board class. That is the only way to guarantee force Core Data to guarantee that grid will always be populated when you access it.
[Edit:
That last is highly theoretical. Using a transient property ensures that Core Data tracks the property such that the accessing the property will cause a fault to fire and provide the data. However, in practice accessing any modeled property will reliably fire the fault and unmodeled methods are always available (see below.)
You can also use:
+[NSManagedObject contextShouldIgnoreUnmodeledPropertyChanges:]
… to force a context to watch unmodeled properties. However, that can cause unanticipated and unmanaged behavior if the unmodeled properties have side effects.
I think that it is good practice to use transient properties whenever possible to make sure everything is covered.]
Update:
Okay, but what if I have an instance method that's not a property
accessor, like doSomething above? How do I make sure I have a real
object before I call it?
I think you're over thinking this and my cumbersome explanation didn't help any.
Core Data manages all these issues for you. I've been using Core Data as long as there has been a Core Data and I have never run into any problems. Core Data wouldn't be much use if you had to constantly stop and check if the objects were faults or not.
For example, I set up a simple model with classes like so:
Alpha:
#class Beta;
#interface Alpha : NSManagedObject {
#private
}
#property (nonatomic, retain) NSNumber * num;
#property (nonatomic, retain) NSString * aString;
#property (nonatomic, retain) NSSet *betas;
-(NSString *) unmodeledMethod;
#end
#interface Alpha (CoreDataGeneratedAccessors)
- (void)addBetasObject:(Beta *)value;
- (void)removeBetasObject:(Beta *)value;
- (void)addBetas:(NSSet *)values;
- (void)removeBetas:(NSSet *)values;
#end
#implementation Alpha
#dynamic num;
#dynamic aString;
#dynamic betas;
-(NSString *) unmodeledMethod{
return #"Alpha class unmodeledMethod return value";
}
#end
Beta:
#class Alpha;
#interface Beta : NSManagedObject {
#private
}
#property (nonatomic, retain) NSNumber * num;
#property (nonatomic, retain) NSSet *alphas;
-(NSString *) unmodeledMethod;
-(NSString *) accessModeledProperty;
#end
#interface Beta (CoreDataGeneratedAccessors)
- (void)addAlphasObject:(Alpha *)value;
- (void)removeAlphasObject:(Alpha *)value;
- (void)addAlphas:(NSSet *)values;
- (void)removeAlphas:(NSSet *)values;
#end
#implementation Beta
#dynamic num;
#dynamic alphas;
-(NSString *) unmodeledMethod{
return [NSString stringWithFormat:#"%# isFault=%#", self, [self isFault] ? #"YES":#"NO"];
}
-(NSString *) accessModeledProperty{
return [NSString stringWithFormat:#"\n isFault =%# \n access numValue=%# \n isFault=%#", [self isFault] ? #"YES":#"NO", self.num,[self isFault] ? #"YES":#"NO"];
}
#end
Then I created an object graph of Alpha object with a related Beta object. Then I restarted the app and ran a fetch of all Alpha objects. Then I logged the following:
id aa=[fetchedObjects objectAtIndex:0];
id bb=[[aa valueForKey:#"betas"] anyObject];
NSLog(#"aa isFault= %#",[aa isFault] ? #"YES":#"NO");
//=> aa isFault= NO
NSLog(#"\naa = %#",aa);
//=> aa = <Alpha: 0x63431b0> (entity: Alpha; id: 0x6342780 <x-coredata://752A19D9-2177-45A9-9722-61A40973B1BC/Alpha/p1> ; data: {
//=> aString = "name 2";
//=> betas = (
//=> "0x63454c0 <x-coredata://752A19D9-2177-45A9-9722-61A40973B1BC/Beta/p7>"
//=> );
//=> // ignore fetchedProperty = "<relationship fault: 0x6153300 'fetchedProperty'>";
//=> num = 0;
//=> })
NSLog(#"\nbb isFault= %#",[bb isFault] ? #"YES":#"NO");
//=> bb isFault= YES
NSLog(#"\nany beta = %#",[[bb class] description]);
//=> any beta = Beta
NSLog(#"\n-[Beta unmodeledMethod] =\n \n %#",[bb unmodeledMethod]);
//=> -[Beta unmodeledMethod] =
//=> <Beta: 0x639de70> (entity: Beta; id: 0x639dbf0 <x-coredata://752A19D9-2177-45A9-9722-61A40973B1BC/Beta/p7> ; ...
//=>...data: <fault>) isFault=YES
NSLog(#"\n-[Beta accessModeledProperty] = \n %#",[bb accessModeledProperty]);
-[Beta accessModeledProperty] =
//=> isFault =NO
//=> access numValue=2
//=> isFault=YES
NSLog(#"\nbb = %#",bb);
//=>bb = <Beta: 0x6029a80> (entity: Beta; id: 0x6029460 <x-coredata://752A19D9-2177-45A9-9722-61A40973B1BC/Beta/p7> ; data: {
//=> alphas = "<relationship fault: 0x60290f0 'alphas'>";
//=> num = 2;
//=>})
Note that:
Both aa and bb are set to the expected class even though I did a generic object assignment. The context ensures that the fetch returns the proper class.
Even bb's class is Beta it reports as a fault meaning that the object represents an instance of the Beta class but that none of it's modeled properties are populated.
The bb object responds to the unmodeledMethod selector even though within the method it still reports as a fault.
Accessing the modeled property of Beta.num converts bb from a fault even before the call is made (the compiler sets it to trigger) but as soon as the access is done it reverts back to a fault.
The objects in the relationships are not only faults but not the same objects returned by accessing the relationship. In Alpha.betas the Beta object has the address of 0x63454c0 whereas bb has the address of 0x639de70> while it is a fault. After it converts from a fault and then back again, it's a address is 0x6029a80. However, the managedObjectID of all three objects is the same.
The morals here are:
"faults" are more about the state of a managed object and less about the actual class. Depending on how you access the object, you might get the actual subclass or you might get an instance of the hidden _NSFault… classes. From the coders perspective, all these different objects are interchangeable.
Even if a managed object reports as a fault, it will still respond to unmodeled selectors.
Accessing any modeled property causes the fault to fire and the object becomes fully active.
Core Data does a great deal of object swapping behind the scenes that you can't control and shouldn't worry about.
In short don't worry about unmodeled properties and methods. They should work transparently. It's best practice to use transient properties especially if those properties have side effects with modeled properties. You can force a context to track unmodeled properties but that can cause unnecessary complexity.
If you have doubts, just perform test yourself on faults to ensure that your class works.

Difference between class property mVar and instance variable self.mVar

I am some what confused as to the difference between accessing an instance variable via self or just by name (when working inside the class).
For instance, take this class:
//In .h file:
#interface Register : NSObject {
NSString *mName;
}
- (id) initWithName:(NSString *) name;
//In .m file:
- (id) initWithName:(NSString *)name
{
if (self == [super init])
{
mName = name;
}
return self;
}
What's the difference between accessing the instance variable via
self.mName = name;
vs
mName = name;
Which isn't a #property and is not #sythenize'd.
Say it is this though, per this example:
//In .h file:
#interface Manange_My_ViewsViewController : UIViewController {
IBOutlet UILabel *countLabel;
}
#property (nonatomic, retain) IBOutlet UILabel *countLabel;
//In .m file:
#synthesize countLabel;
- (void) updateLabel:(NSUInteger)count
{
countLabel.text = [NSString stringWithFormat:#"%d", count];
}
But say I accessed countLabel as:
self.countLabel
What would be the difference?
Edit: Third example per users' answer:
Say it the iVar wasn't an IBOutlet:
//In .h file:
#interface Fake : NSObject {
NSString *mVar;
}
#property (nonatomic, retain) NSString *mVar;
//In .m file:
#synthesize mVar;
mVar = #"";
VS
self.mVar = #"";
Or is it the same - that in the first we are accessing the actual instance variable and in the second we're actually going through the auto created setter (via #synthesize)?
Thanks all!
Edit: Update in response to Peter Hosey ...
So your thinking the convention of mVarName is bad? I took that from my C++ days.
But what about the case when you do?
-(void) someMethod:(int) x
{
x = x;
}
You can't do that (Say 'x' is also a class variable)
But you can do:
-(void) someMethod:(int) x
{
mX = x;
}
But your saying its better to do:
-(void) someMethod:(int) x
{
self.x = x;
}
What's the difference between accessing the instance variable via
self.mName = name;
vs
mName = name;
The first is property access syntax. It translates to an accessor message to the object (in this case, self). That is, that statement implicitly translates to this message expression statement:
[self setMName:name];
(Awkward accessor names like that are why “mName” is a poor name for a property. There is property declaration syntax to work around that, letting you name the property “name” and your instance variable “mName” and map one to the other.)
The second example directly accesses the instance variable—no accessor message.
Which isn't a #property and is not #sythenize'd.
Say it is this though, …
If no property named “mName” is declared for a class, then you can't use property access syntax to access a property by that name on an instance of that class.
And it doesn't matter whether you synthesize the accessors, hand-wave them to a superclass with #dynamic, or define them yourself. That's how the object will respond to the accessor message, but the accessor message the compiler generates will be no different (since a property access could just as easily come from outside the class as from inside it).
Say it the iVar wasn't an IBOutlet:
That doesn't matter. IBOutlet only means anything to IB. Everything else doesn't care.
In fact, IBOutlet is currently just a macro that expands to nothing. After your code gets preprocessed, the word “IBOutlet” is no longer there, so the compiler never sees it. That's how little a difference it makes to anything but IB: None at all.
Edit in response to question edit
I said mName is bad as a property name, because of the accessor names that follow from it. The name of an instance variable is a separate issue, particularly since the property and ivar don't have to have the same name.
For a variable, be it an instance variable or a local variable, the choice of name or m_name or mName is purely a style choice.
someMethod: is generally the accessor, setX:. Within that method, self.x = x, which is [self setX:x], causes infinite recursion. So don't do that.
When someMethod: isn't the accessor (or init or dealloc), using the property is just fine and generally preferable. However, in that case, you're not likely to give one of its arguments the same name as an instance variable. When such a case could occur, name the local variable more specifically, because its purpose is more specific. This, too, is a style issue.
When it is the accessor, I name the local variable newX, having named the instance variable the same as the property, x. This is my own personal style; as I said, naming the property x, the ivar mX, and the local variable x is fine too (aside from the excessive brevity of this example).
OK, first off is the basic difference:
mVar = var;
This is just changing a value. That's it.
self.mVar = var;
This is equivalent to:
[self setMVar:var];
In other words, one invokes a method, the other does not. Using the #property syntax can give you some really neat benefits. For example, you get key-value coding compliance for free. That means that another object can observe this object's mVar property, and be automatically notified whenever it changes, without you doing anything. You don't get this if you just access the ivar directly. (Unless, of course, you implement it yourself. But why would you do that?)
You also get semi-free memory management. If you declare a property as (retain), then you don't have to [newValue retain] yourself. The synthesized method will do this for you (in both cases, you'd still have to [ivar release] in your dealloc method).
You also can get some degree of thread safety. If you don't declare a property as (nonatomic), then it is (by default) atomic (although that keyword does not exist; it's implied). That means that reading/updating the value of the property is an atomic operation. If you were to just access the ivar directly, you'd have to implement the atomicity yourself with a lock.
Basically, using the synthesized methods gets you some really neat stuff for free. The only reason I'd say to not use the #property syntax is if you have irrefutable evidence that invoking those methods is a bottleneck in your code. However, you'll be really hard pressed to come up with a situation where that would be the case.
First of all, with a read-only property--which an IBOutlet essentially is--it does not matter as much.
The key difference is that the property is actually calling the accessor method while the instance variable is being accessed directly.
Thus, for setting a retain property, using self and the accessor will release the old object and retain the new one. Setting the instance variable directly will NOT impact the retain counts of any objects.
Using #synthesize will generate standard accessors for you.
The key reason to use properties is that, since they are accessors, they can be read and/or modified from outside the class.