What is the strong property attribute - iphone

I am using the Xcode beta for developers, and am noticing some subtle differences. Among them is a new attribute for declared properties.
#property(strong)IBOutlet NSArrayController *arrayControl;
My question is: what does the strong attribute mean?? Does it replace some older one, or is it something entirely new? I have searched through google and the developer documentation and havent been able to find anything. Until i know what it is i am hesitant to use it.
Thanks in advance

It's a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.

A strong reference is a reference to an object that stops it from being deallocated. In other words it creates a owner relationship. Whereas previously you would do this:
**// Non-ARC Compliant Declaration
#property(retain) NSObject *obj;**
Under ARC we do the following to ensure a class instance takes an ownership interest a referenced object (i.e. so it cannot be deallocated until the owner is).
**// ARC Compliant Declaration
#property(strong) NSObject *obj;**

As we know, we cannot release any object in an ARC-based project in iOS 5.
So when we want to retain any object for further use at a later stage and don't want ARC to remove the object from memory, then we set the property for the object as "Strong".

Related

Different memory management ARC / no ARC

I have to convert simple ARC code to non ARC. While it was relatively straight forward I missed an instance variable assignment self.var = xxx, instead I wrote var = xxx.
While in the ARC version it did not cause any trouble - in the non ARC version it certainly caused a crash.
Does that mean that it is actually OK to assign instance vars in ARC without the self. so they get retained?
Thanks!
ps what's the best source to learn how to program in ARC so one avoids abvious errors - so far I did not find any problem at all but I am getting nervous that I might have missed something
Does that mean that it is actually OK to assign instance vars in ARC without the self. so they get retained?
Yes, kind of.
id obj_;
It is same as this.
id __strong obj_;
obj_ has strong reference for assigned object. The assigned object will not be dealloc-ed until the owner object for the ivar is dealloc-ed.
Please refer to LLVM document or the Apple's ARC reference that is still under NDA.
Automatic Reference Counting forbids explicit message send of ‘dealloc’
I have shared a trick to enable older library compilation in new iOS5 SDK.
Click on the Project.
Click on the target.
Select build phases tab.
Select the multiple files in which you want to turn off ARC.
Press ENTER / Hit Enter key
Type “-fno-objc-arc” ( without quotes, as shown in image )

iPhone - Is there a way to know if a reference is (still) valid?

Let's say I assign an instance var with an object given in parameter. I don't know what this object is, so I don't want to retain it. But, that reference I have to that object can be invalid at some time, for example if the object is released, or is about to be released (autorelease pool). So, inside my class instance, can I know if the reference I have kept into an instance variable can be used without any risk of crash?
You should retain it and release it when you no longer need it. That is exactly what retain is for.
Kris Van Bael is right, no matter if you know what the object is, if you want to have ownership of it (if it's up to you to ensure that the object is alive), you must retain it. Release it when you don't need it, and set the reference to NIL (for security).
But their is an exception !
Sometimes you don't want to have ownership, the most common example is the delegate.
You don't want to retain your delegate, because it probably already retains you, and if both objects release each other in the dealloc method, your app will leak.
But in this case, you shouldn't care about the delegate being deallocated : the delegate should set your "delegate" property to nil in it's dealloc method.
So
if you have ownership on the object : retain, no choice !
if the object has ownership on you : assign, and don't worry !
This approach is really dangerous. If your app is not able to track object life cycle, then you must change the code in order to have control of this.
Anyway answering to your question: you can protect your instance variable by extra retaining it in your class and then releasing it when it is no more needed. So you don't need to do the check you are asking for.
You should set any released reference to NIL and check for NIL.

How can I avoid redundancy while declaring new class attributes in Objective-C?

In my code, every time I need a new object attribute for my class, I typically copy/paste its name in 4 different places!
The declaration in the header file (NSObject * myObject;)
The #property() line
The #synthesize() line in the implementation
Releasing it under dealloc: (only for objects of course)
I do this because it works, not because I completely understand what's going on. I do know that the declaration in the header file allows other classes to see its attributes, the property specifier determines how its getter/setter methods will be constructed. And the synthesize line actually builds those getter/setter methods. I also know that primitive types should use (nonatomic,assign) instead of (nonatomic,retain), but I have no clue when I should omit the nonatomic.
What can I do to avoid redundancy in my code. If I change or add a variable in my class I have to check 4 different places, and it gets old really fast. Are there any key strokes to make this process faster? Are there lines of code I can simplify or combine to obtain the same result?
Accessorizer will automate a lot of this for you.
In the latest version of Clang (Ships with XCode 4, not in XCode 3 yet) you get default #synthesize as well as default ivar creation. The default ivar creation already works, but not on the simulator. With both of these features all you need to do is add the #property line and deal with the memory management in dealloc
As far as nonatomic vs atomic. atomic is the default, and what happens when you leave off the nonatomic annotation. Atomic guarantees that the value is completely set before allowing anything to access it, nonatomic doesn't. Atomic is only useful in threading situations, and is slightly slower in singlethreaded applications.
It's important to understand what each of those lines of code does. They are not all the same and they are not necessarily redundant. One thing that will help is to use the correct terminology — for example, with NSObject *myObject; you're probably referring to an instance variable declaration.
First and foremost, a #property declaration in an #interface lets you say that instances of a class expose a piece of state. It doesn't say much about the implementation of that state, only that it's exposed by instances of your class and the API contract (memory management, atomicity, methods) for the state.
The #synthesize directive tells the compiler to create or use a specific instance variable as storage for a declared #property. This does not need to be how you provide storage for a property. For example, Core Data provides its own storage for modeled properties, so you use #dynamic for those instead. You also don't need to use an instance variable with the same name as your #property — to extend your example above, you might name your instance variable myObject_ while naming your property object and that's perfectly fine.
Finally, you send the instance variable -release in -dealloc — for an object-type property marked retain or copy — because you've said you'll manage its memory. You're not releasing the property, you're releasing the storage. If you implemented the storage some other way, you'd clean it up some other way.

Memory Management on the iPhone

I'm sorry to ask such a simple question, but it's a specific question I've not been able to find an answer for.
I'm not a native objective-c programmer, so I apologise if I use any C# terms!
If I define an object in test.h
#interface test : something {
NSString *_testString;
}
Then initialise it in test.m
-(id)init {
_testString = [[NSString alloc] initWithString:#"hello"];
}
Then I understand that I would release it in dealloc, as every init should have a release
-(void)dealloc {
[_testString release];
}
However, what I need clarification on is what happens if in init, I use one of the shortcut methods for object creation, do I still release it in dealloc? Doesn't this break the "one release for one init" rule? e.g.
-(id)init {
_testString = [NSString stringWithString:#"hello"];
}
There is a neat acronym to remember what you have to release
N.A.R.C - new, alloc, retain, copy.
If it's not created with alloc, new, copy, mutableCopy then you're not responsible for releasing it.
This site has some good quick overviews of things like memory management.
Here's a quote from cocoadevcentral:
If you create an object using the
manual alloc style, you need to
release the object later. You should
not manually release an autoreleased
object because your application will
crash if you do.
Just to clarify things a bit. When you get an object through N.A.R.C. as sylvanaar says you do need to release it. In other cases you are getting an autoreleased object that will be released automatically at some later time. That will be bad in the code you presented here, because you do want this string to stay around at least as long as your object. So you actually need to do an explicit retain to keep it alive for your object.
That is not directly answering your question, but rather anticipating the next one ;-)
If you set an attribute with an autorelease, the object in the attribute can die at anytime beyond the immediate scope. Convenience methods i.e. ones that start with a type: string, array, dictionary etc, return autoreleased objects. You only use autoreleased objects when you don't care whether or not they survive beyond the present scope.
What you really need to do in this case is use accessors, either the synthesized or custom, to manage your retention automatically.
If you do:
#property(nonatomic, retain) NSString *_testString; // .h
#synthesize _testString; //.m
then in code use the reference form:
self._testString = [NSString stringWithString:#"hello"];
... then the only place you have to release _testString is in dealloc. The compiler will create synthesized accessors which will automatically manage the properties memory for you.
By the way, you should not use underscores for names. Apple reserves underscore names for itself so you can get a naming collision.
In the first part of the example you do indeed have to have a release for the string somewhere.
In the second part of the example because its an autoreleased you don't need to call the additional release in the dealloc method. This will actually cause a crash as you are attempting to send a message to something that no longer exists...
On the contrary, you need to retain the object you get from stringWithString:. As you correctly noted, you don't own that object and thus don't need to release it. But because you don't own it, it's free to disappear at any time, leaving you with a crash if you're lucky (and a very odd bug if you're not). So you need to retain the object, and then you do need to release it in dealloc.
All of this is explained very well in the memory management guide. I suggest you read it over a couple of times. It's not very long or difficult, and once you internalize it, you'll never have to wonder again.
The rule is if you create an object with new, alloc, copy or you retain it, you need to release it. Objects created in any other way must not be released.
So in your specific case, you would not need to release your string created with stringWithString.
By the way, I would recommend the Cocoa and Objective-C: Up and Running book for learning more about things like this. Great introduction if you are new to Cocoa programming.

Which iPhone OS memory management rules and how-to's do you know?

Currently I am jumping into the ice cold water called "memory management in iPhone OS".
Here's one rule i've learned:
Every time I see an alloc in my method, I will release that corresponding variable at the bottom of the method.
Every time I create an #property(...) in my header file which says copy or retain, I put a release message on that variable into the dealloc method.
Every time I have an IBOutlet, I do the same thing. Only exception: If the IBOutlet has something like #property(... assign), or in other words: If it has the assign keyword at all. Then I don't care about releasing it in the dealloc method.
I feel that there are many more good rules to know! Just write down what you have. Let's scrape them all together. Links to great descriptions are welcome, too.
Actually, any time you initialize an object and the method name includes "init" you are responsible for releasing it. If you create an object using a Class method that does not include the word "init" then you don't.
For example:
NSString *person = [NSString stringWithFormat:"My name is %#", name];
does not need a release. But:
Person *person = [[Person alloc] init];
needs a release (as you stated in your question). Likewise:
Person *person = [[Person alloc] initWithName:#"Matt"]];
also needs a release.
This is a convention, not a rule of the language, but you will find that it is true for all Apple-supplied APIs.
The rules I use
Release all objects you create using a method whose name begins "alloc" or "new" or contains "copy".
Release all objects you retain.
Do not release objects created using a +className convenience constructor. (The class creates it and is responsible for releasing it.)
Do not release objects you receive in other ways E.g.
mySprockets = [widget sprockets];
If you store an object you receive in an instance variable, retain it or copy it. (Unless it's a weak reference - just a pointer to another object, usually to avoid cyclical references.)
Received objects are valid within the method they are received in (generally) and are also valid if passed back to the invoker.
Some good links:
http://www.gehacktes.net/2009/02/iphone-programming-part-2-objective-c-memory-management/
http://mauvilasoftware.com/iphone_software_development/2008/01/iphone-memory-management-a-bri.html
Memory management can seem daunting when you're seeing segfaults spring from every seeming innocent line of code, but it's actually pretty easy once you get the hang of it. Spend a little time reading this page and then Apple's documentation, and you should be writing bug-free code in no time.
I tend to create only autoreleased objects, either by using a class method or by autoreleasing it immediately after creation, unless I can state a reason not to. For example:
I am assigning it to a member variable because I intend to hold onto it for a while.
I am only creating it to pass it on immediately to another method, and I send it a release message right after that method call.
For performance reasons, I need to free that memory before the nearest NSAutoreleasePool will be released, such as creating a large number of objects inside a loop or the objects are holding onto a large amount of data (e.g., images).
That way, I am less likely to leak objects. By default, I create them autoreleased, and when I make the deliberate decision not to autorelease them, I am immediately faced with the question of where they will be released.
For object properties, rather than releasing them in my dealloc method, I like to assign nil to them. That way, retained or copied properties are sent a release, while assigned properties are simply overwritten, and I don't have to update my dealloc method if I change the property to/from retained.