Reference counting in Cocoa - objective-c

I assume according to "Cocoa design patterns" book i'm reading that the retain function is implemented using something like this :
- (int)retainCount
// Returns the receiver's current reference count
{
int result = 1; // receiver not in table, its count is 1
void *tableValue = NSMapGet(
[[self class] _myRefCountMapTable], self);
if(NULL != tableValue )
{ // if receiver is in table, its count is the value stored
result = (int)tableValue;
}
return result;
}
- (id)retain
// Increases the receiver's reference count
{
// store the increased value in the table
NSMapInsert([[self class] _myRefCountMapTable], self,
(void *)([self retainCount] + 1));
return self;
}
As the example imply every reference object has the same self member.
How does that happen ? maybe I don't understand the meaning of self - I though it's like "this" in C++.
If I just use assignment operator (A=B) Does it copy the pointer(self) and that's it ?
I though it would use "copywithzone" and it's relatives and the "self" members won't be equal.
Moreover, I though copywithzone is like copy constructor in c++.
I guess i'm confusing between the 2 worlds.

As the example imply every reference object …
There is no such thing as a “reference object”. I suspect that's not what you meant, so please clarify.
has the same self member.
Objects do not have members (instances have instance variables, which are similar in concept but not the same in implementation).
self is not a “member”, nor is it an instance variable. Note that classes have self as well. self is a special hidden argument to the message, containing the object that is the receiver of the message.
And no, self does not refer to every object at once. If you send the same message to two different objects, even of the same class, the self argument will contain a different pointer in each message.
maybe I don't understand the meaning of self - I though it's like "this" in C++.
As I understand “this”, yes. self is the object that received the message—in your examples, the object that something is retaining or asking the retain count of.
If I just use assignment operator (A=B) Does it copy the pointer(self) and that's it ?
The pointer copied will only be self if B is self. That is, if you say A = self, then it will copy the self pointer to A. If you say B = self and then you say A = B, same thing, since B and self contain the same pointer. If you had not said B = self, then B is probably some other value, so that other value is what will be copied to A. And that's assuming A and B are pointer variables.
It will copy the value (pointer) you tell it to copy. Nothing else.
I though it would use "copywithzone" and it's relatives and the "self" members won't be equal.
No. The object is only sent a copyWithZone: message (do not omit colons—they are significant) when something sends it a copyWithZone: message. The most common way is to send it a copy message, as that will send a copyWithZone: message in turn.
Furthermore, even a “copy” does not always copy the object. Immutable objects can implement copyWithZone: to return [self retain] instead.
However, plain assignment never copies the object. It only copies the pointer.
Moreover, I though copywithzone is like copy constructor in c++.
Roughly. I don't know enough C++ to say how much like it it is.

I remember having heard that you shouldn't make any assumptions on the retainCount. :-)
self is indeed very similar to this.
Assignment just copies the pointer, and it's the same in C++.
NSObject *objA =[[NSObject alloc] init];
NSObject *objB = objA;
objA and objB reference the same object.
Not that your code example uses [self class], so they'd use one table per class for all instances of that class.

Related

Why alloc method can add retain count

When we call alloc with a Class, I know that count of Object will +1. For example: NSObject *obj = [NSObject alloc];, The reference count of obj will be 1. I read the source code, but I can't find some code that can tell me why alloc can add the reference count. And some blog said alloc will call retain method, so it can +1. But I can't find some code can prove this. Can some one tell me why alloc will add reference count?
You cannot find generic code that adds one in +alloc. Usually inside +alloc the object is newly created and gets the RC 1. (So you can say that 1 is added, because the object before its creation has an RC of 0. Of course, this is not formally correct, because before the creation there is no object, therefore it cannot have an RC. Akin of the zero is null antipattern.)
However, classes can overwrite +alloc to return an existing object instead of a new one. For example this has been done in the past for implementing singletons. In such a case +alloc had to signal the new reference (+alloc does an ownership transfer) and really had to add 1. Something like this (sample code):
+(id)alloc
{
if(mySingleton==nil) // it is not already created
{
return mySingleton = [super alloc];
}
return [mySingleton retain]; // ownership transfer
}
I think the idea of saying "+1" instead of "1" in some articles is, that you should view every reference separately. So there is no absolute value of RC. Whatever you do with a reference and its object is relative to the situation before you did it. For this reason some authors always describe the RC with "+1" and "-1". Of course, this is meaningless, if an object is newly created.
alloc does not increase the count. There is not any object until you call alloc, so there is nothing to count. The object comes into existence with one reference, and so it comes back from alloc with a retain count of positive 1.
(Conversely, if there is ever less than one reference, the object is dead.)

Are selector IDs sensitive to argument types?

When you retrieve the ID of a selector with #selector(), is the selector value different depending on the types of the arguments?
Here's what I mean. I have a method that takes an object reference and a selector, then calls it with a parameter:
-(void)CallLater:(NSObject*) Obj Sel: (SEL)Sel
{
//Some stuff, then:
[Obj performSelector: Sel withObject: SomeOtherObject];
}
I'm using this method with a selector to a function that takes a typed object reference, not an id:
-(void)MyMethod: (MyObject*) a
{
}
[self CallLater: self Sel:#selector(MyMethod:)];
It seems to work, but my senses are tingling. In a statically typed language like C# this would be a foul, an upcast - CallLater is expecting a selector for a function that takes an id and I'm giving it a function that takes a MyObject.
On the other hand, the compiler does not complain, and both id and concrete object references seems to be mere pointers deep down, trivially castable to one another. Then again, there are many fouls that Objective C compiler does not complain about.
So the real question is - is it safe? Language lawyers welcome.
It's safe; objects are objects. A selector parameter for an NSObject * is exactly the same as a selector parameter for a MyObject *.
If you want MyMethod to verify that it's being called with an object of a particular type, it should do a NSParameterAssert on it:
NSParameterAssert([obj isKindOfClass: [MyObject class]]);
Personally, I rarely do this check. It's enough that the actual object acts like the type I want it to be, and if it doesn't I'll get a runtime error (usually unrecognized selector). You'll get a compiler warning in the simple cases, and it's worth paying attention to this warning (and silencing it with an id cast when necessary).
I'm a bit confused here about your use of id in your question, so I want to make sure you understand this: An NSObject * is exactly as much an id as a MyObject * is. id is a generic instance pointer class, whereas NSObject * is a NSObject instance (or a subclass of NSObject). You can have objects that don't descend from NSObject. But you're unlikely to ever have to know this.
Other notes, re: convention:
Selectors (both the name and parameters) start with lowercase letters, so CallLater:Sel: should be callLater:sel:.
Variable and parameter names start with lowercase letters; Obj above should be obj.
Class names do start with an uppercase letter. :)

objective c memory manegment when returning objects from another object

I am having problem with understanding one concept of memory managment, because I am new to objective C. For instance lets say I have a class Bar and Foo.
in main function I call:
Foo *foo = [bar getFoo]; //In my bar method I return foo
[foo retain];
[foo callMethod];
[foo release];
I know this is right way to do it. But why do we have to retain it after we get it from another object, does not this mean returning object has retain count 0 ? so we have to reatin it to count 1 to use it? but if it has reatin count 0, how do we know it is still there. We can assume since it is the next line that increment retain count that the object memory wont be realocated, but what if we have multi-threading program?
When an class method returns an object, it will autorelease it so you don't have to bother; typically:
- (Foo *)getFoo
{
return [[_foo retain] autorelease];
}
If you are only using foo for the lifetime of the calling method you don't need to retain it, as it won't be autoreleased until next time through the run loop, so your code should actually be:
Foo *foo = [bar getFoo]; //In my bar method I return foo
[foo callMethod];
If, however, you want to hold foo for a while, outside the scope of the calling method, you need to retain it and then release it sometime later.
One more thing; the convention for getter method names is simply "name", so your setter should be setFoo and your getter would be foo. Keeping to the naming conventions is a good idea as it lets you know what a method does, in say 7 months time, and tools like static analysis understand the conventions.
The method getFoo doesn't return an object with a 0 retain count. It returns an object with a +0 retain count which means that:
the object's retain count is not null (otherwise, the object wouldn't exist)
and the retain count wasn't altered by the invocation of the method, or if it was, it was in a balanced way (with as many release/autorelease as retain/alloc/new/copy).
Thus the lifetime of the object entirely depends on where and how it is retained. We don't know how long the object will be valid as any method invocation could release the object.
For example, let's consider the following code:
id anObject = [anArray objectAtIndex:0];
[anArray removeObjectAtIndex:0];
The object anObject isn't retained any more by the array as we removed it. Therefore it may have been destructed (but maybe it wasn't because it is still used somewhere else).
Generally, when getting an object from a method (other that alloc, copy, new or retain), we can assume that:
either the object was retained then autoreleased,
either the object is retained by the object that returned it.
So we know the object foo is valid until we return from the current method/function or we invoke a method/function that alter the state of the object bar, whichever comes first. After that, it may have been destructed.
So in your case, you can safely omit the retain/release pair.
However, it is very difficult to guaranty that an object doesn't get released unless we know the implementation of every method we invoke. Therefore, retaining (then releasing) every single object we get is the safer approach and that's what the compiler will do when you enable ARC (Automatic Reference Counting).
But that would require you to write a lot of retain/release and your code would become difficult to read, understand and maintain. Moreover, the more code you write, the more bugs you get (unless you never write bugs).
In conclusion, you don't need to retain an object unless you have a reason to suspect it could vanish otherwise.

Accessor that returns value vs accessor that returns reference?

From my understanding both of the following getter methods reference the actual object.
So what is the difference between the two?
When and why would you want to use the second getter method?
- (MyObject *)myObject
{
return _myObject;
}
- (void)getMyObject:(MyObject **)myObject
{
if (!myObject)
{
*myObject = _myObject;
}
}
You would not use the second one.
Unless you like confusing people/yourself at a later date by not following the standard conventions.
It would make more sense if there was another piece of data that could also be returned for example look at NSManagedObjectContext
- (BOOL)save:(NSError **)error
The important result of the method is YES/NO did it save, but then we can also get an NSError object to inspect if there was an error.
In Objective C, an "object" is a C pointer, so an object value is actually already the same as a structure reference (an opaque structure with hidden fields if you want the code to be portable between Objective C runtimes).
So there is no "versus".
YouR first example is both.
There are special situations when an algorithm needs a reference to a reference, or a pointer to a pointer, but not very commonly. That would be your second example.

Why create custom init when ivars/properties can be set from outside the instance?

I'm reading an Objective-C book and I have a question that the book doesn't seem to really answer.
Let's say I have two custom-made classes.
The first class is called ClassA. It has both the .h and .m files of course. The second class is called ClassB. It also has both .h and .m files.
Somewhere in the code, 'ClassA' has this method:
-(IBAction)displaySomeText:(id)sender {
ClassB *myNumber = [[ClassB alloc]init];
NSString *numberString = [myNumber storedNumberAsString];
// storedNumberAsString is just a method that returns a string object that holds
// myVariable.
[textView insertText:numberString];
//textView is a object I created that just displays some text on screen.
[myNumber release];
}
The book tells me that ClassB should have a method:
-(id)init {
[super init]; //I know why this is done, the book explains it well.
myVariable = 42; // I created this variable already in the ClassB .h file
return self;
}
Now, when in the Interface Builder I click the buttons I connected, etc. It works, the number displayed is 42.
My question is, why do I have to create an -(id)init method for ClassB, if I can do the following in ClassA's method:
-(IBAction)displaySomeText:(id)sender {
ClassB *myNumber = [[ClassB alloc]init];
myNumber.myVariable = 42; //I just do this to skip the -(id)init method.
NSString *numberString = [myNumber storedNumberAsString];
[textView insertText:numberString];
[myNumber release];
}
Doing this, it still displays the same value: 42. I can change it to whatever I like. So why not just use the init inherited from NSObject and just do the simple way myNumber.myVariable = 42?
Suppose that the value of the instance variable were something more complicated than an integer. Suppose it involved reading a string from a file, or getting some information over the network, or just doing some arithmetic. In that case, it wouldn't make sense to have ClassA be responsible for setting that value correctly. That would break the encapsulation that makes it useful to have separate classes in the first place.
In this extremely simple case, you're quite right, there may be no reason to have a custom initializer for ClassB, but in general, a class should itself be responsible for its state being set up correctly. Foisting that responsibility off on other classes means that those others need to know about the internals of the first, meaning the two may be too tightly coupled.
In some cases, the value of the ivar might be a piece of information that is known only to ClassA, or needs to be calculated based on such a piece of information. Then you should create a custom initializer for ClassB which receives that value, e.g., - (id) initWithInteger: This would become the "designated initializer", and you would then override -[ClassB init] to call it with some reasonable default value.
If instances of ClassB do not have to have anything initialized (other than to nil/zero), you do not need to create an explicit init method for ClassB. In this case the question is whether setting myVariable to 42 is ClassB's answer to life, the universe, and everything, or whether myVariable is just a field in ClassB that could be set to any value.
That is, the issue is conceptual, not of physical significance. If conceptually the value 42 "belongs" to ClassB, then there should be an init method for ClassB that sets it. If that specific value has more meaning to ClassA than to ClassB then some method of ClassA should set it. If you do it "wrong" the code still works fine, but your design is slightly less elegant, slightly less extendable, slightly less robust.
This is kind of a tricky issue. I was "brought up" to think that after a constructor (initializer) runs, the object should be ready to go. You should be able to safely call any method on it. Therefore, you need to set up any instance variables in the constructor for which 0 is not a valid value. I like to set them up if they have 0 values anyway, just for sanity, because I never want to bother to know the minute details of every language I work with, like whether they initialize instance variables to 0 automatically.
However, there are some arguments for not initializing some variables.
The initialization is complex, like loading a file or getting data from the network. You want to keep open the possibility of creating an instance and waiting until you're ready to do heavy weight operations.
There are quite a lot of instance variables that are configurable. Your options are to make a constructor with umpteen arguments, or make a constructor with no or a few arguments, and let the caller decide which values should be set to non-default values by property setters.
You need to set up a whole object graph before you can meaningfully initialize a value. That is, initializing the value might have side effects that depend on other related objects. The best solution is to construct each object, then use property setters to set the relationships between objects, then use property setters to initialize attribute values.