Can an Objective-C block object have an associated object? - objective-c-blocks

If it can, are there any gotchas to using it?

Yes you can. I just tried it. This makes sense, since blocks are instances of NSBlock (a private class), which itself inherits from NSObject.
However, my naïve test seemed to indicate that the associated object was not un-associated when the block was deallocated. (Although it's possible that I was never hitting the block's -dealloc method)
I'll keep experimenting and try some more stuff.

Related

Objective-c: Reference to ivar persistent? Good idea?

I have a situation where I'm keeping references to ivars which need to be persistent. In one object, I have an array of pointers to ivars in another object, which are used over the entire lifetime of the program. In other words, I'm not just passing a reference to retrieve a value -- I'm keeping the pointers around.
Is this a valid? Is it possible that the ivars might move? Are there cases where objects instantiated objects are moved around at runtime unbeknownst to the program? Or, do objects stay exactly where they are created. If the later is the case, is there any reason not to use references the way I am?
I'm using ARC.
Note: This probably wasn't a good way to design this to begin with, but... it's all done and working 99%! (except for a nasty crash which reboots the entire phone... )
Objects and their instance variables don't move once created. However, you also need to keep a strong reference to the object that holds the ivar. Otherwise, the object might be deallocated, leaving you with a dangling pointer.
Note that it is generally a very bad idea to have pointers to another object's insntance variables.
While there's no technical problem with accessing the ivars from outside (as rob stated) there's still the architectural design to consider: The approach you've taken breaks encapsulation. Additionally it is very uncommon for Objective-C.
So regarding maintainability of your code I would recommend to refactor the code. In Objective-C there's no friend declaration as in C++, so it's unusual to access ivars from outside the declaring class.
Let's say an object of class A wants to access the ivars of an object of class B persistently (in your example).
What you normally do is create a property (with the strong annotation, like #property (strong) ClassB *myBVar) in class A to reference an object of class B.
If you want to set or read B's properties you use the dot notation or call the getter/setter methods:
myBVar.name = #"Jim";
NSLog(#"Name:%#",myBVar.name);
[myBVar setName:#"Jim"];
NSLog(#"Name:%#",[myBVar name]);
You never call a ivar directly as it's implementation might change.

Do I need to Subclass from NSObject?

I'm starting Objective-C Development and I'm trying to wrap my head around how some things work.
I'm creating a Twitter Client and have a class "Tweet". This is just a DTO - a class that has some variables.
Should this just be a class or should it inherit from NSObject?
Why? Or why not?
Every normal class should subclass from NSObject. Basic memory management like -retain and -release, and runtime introspection like -isKindOfClass:, -respondsToSelector: cannot work without it.
You should, unless you have a very explicit, strong reason not to. In Objective-C, any object can be assigned to an id. But id doesn't guarantee any methods at all, even the standard operations such as allocation, initialization, deallocation and reference counting.
These are implemented by a root class, which is almost always an NSObject.
Also, most of the Cocoa API expects to deal with an NSObject, because it needs to at least retain and release the object.
So you should inherit from NSObject.

In ObjC, how to describe balance between alloc/copy/retain and auto-/release, in terms of location

As is common knowledge, calls to alloc/copy/retain in Objective-C imply ownership and need to be balanced by a call to autorelease/release. How do you succinctly describe where this should happen? The word "succinct" is key. I can usually use intuition to guide me, but would like an explicit principle in case intuition fails and that can be use in discussions.
Properties simplify the matter (the rule is auto-/release happens in -dealloc and setters), but sometimes properties aren't a viable option (e.g. not everyone uses ObjC 2.0).
Sometimes the release should be in the same block. Other times the alloc/copy/retain happens in one method, which has a corresponding method where the release should occur (e.g. -init and -dealloc). It's this pairing of methods (where a method may be paired with itself) that seems to be key, but how can that be put into words? Also, what cases does the method-pairing notion miss? It doesn't seem to cover where you release properties, as setters are self-paired and -dealloc releases objects that aren't alloc/copy/retained in -init.
It feels like the object model is involved with my difficulty. There doesn't seem to be an element of the model that I can attach retain/release pairing to. Methods transform objects from valid state to valid state and send messages to other objects. The only natural pairings I see are object creation/destruction and method enter/exit.
Background:
This question was inspired by: "NSMutableDictionary does not get added into NSMutableArray". The asker of that question was releasing objects, but in such a way that might cause memory leaks. The alloc/copy/retain calls were generally balanced by releases, but in such a way that could cause memory leaks. The class was a delegate; some members were created in a delegate method (-parser:didStartElement:...) and released in -dealloc rather than in the corresponding (-parser:didEndElement:...) method. In this instance, properties seemed a good solution, but the question still remained of how to handle releasing when properties weren't involved.
Properties simplify the matter (the rule is auto-/release happens in -dealloc and setters), but sometimes properties aren't a viable option (e.g. not everyone uses ObjC 2.0).
This is a misunderstanding of the history of properties. While properties are new, accessors have always been a key part of ObjC. Properties just made it easier to write accessors. If you always use accessors, and you should, than most of these questions go away.
Before we had properties, we used Xcode's built-in accessor-writer (in the Script>Code menu), or with useful tools like Accessorizer to simplify the job (Accessorizer still simplifies property code). Or we just typed a lot of getters and setters by hand.
The question isn't where it should happen, it's when.
Release or autorelease an object if you have created it with +alloc, +new or -copy, or if you have sent it a -retain message.
Send -release when you don't care if the object continues to exist. Send -autorelease if you want to return it from the method you're in, but you don't care what happens to it after that.
I wouldn't say that dealloc is where you would call autorelease. And unless your object, whatever it may be, is linked to the life of a class, it doesn't necessarily need to be kept around for a retain in dealloc.
Here are my rules of thumb. You may do things in other ways.
I use release if the life of the
object I am using is limited to the
routine I am in now. Thus the object
gets created and released in that
routine. This is also the preferred
way if I am creating a lot of objects
in a routine, such as in a loop, and
I might want to release each object
before the next one is created in the
loop.
If the object I created in a method
needs to be passed back to the
caller, but I assume that the use of
the object will be transient and
limited to this run of the runloop, I
use autorelease. Here, I am trying to mimic many of Apple's convenience routines. (Want a quick string to use for a short period? Here you go, don't worry about owning it and it will get disposed appropriately.)
If I believe the object is to be kept
on a semi-permanent basis (like
longer than this run of the runloop),
I use create/new/copy in my method
name so the caller knows that they
are the owner of the object and will
have to release the object.
Any objects that are created by a
class and kept as a property with
retain (whether through the property
declaration or not), I release those
in dealloc (or in viewDidUnload as
appropriate).
Try not to let all this memory management overwhelm you. It is a lot easier than it sounds, and looking at a bunch of Apple's samples, and writing your own (and suffering bugs) will make you understand it better.

Why are Objective-C delegates usually given the property assign instead of retain?

I'm surfing through the wonderful blog maintained by Scott Stevenson, and I'm trying to understand a fundamental Objective-C concept of assigning delegates the 'assign' property vs 'retain'. Note, the both are the same in a garbage collected environment. I'm mostly concerned with a non-GC based environment (eg: iPhone).
Directly from Scott's blog:
"The assign keyword will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates."
What does it mean that you don't directly own the delegate object? I typically retain my delegates, because if I don't want them to go away into the abyss, retain will take care of that for me. I usually abstract UITableViewController away from its respective dataSource and delegate also. I also retain that particular object. I want to make sure it never goes away so my UITableView always has its delegate around.
Can someone further explain where/why I'm wrong, so I can understand this common paradigm in Objective-C 2.0 programming of using the assign property on delegates instead of retain?
Thanks!
The reason that you avoid retaining delegates is that you need to avoid a retain cycle:
A creates B
A sets itself as B's delegate
…
A is released by its owner
If B had retained A, A wouldn't be released, as B owns A, thus A's dealloc would never get called, causing both A and B to leak.
You shouldn't worry about A going away because it owns B and thus gets rid of it in dealloc.
Because the object sending the delegate messages does not own the delegate.
Many times, it's the other way around, as when a controller sets itself as the delegate of a view or window: the controller owns the view/window, so if the view/window owned its delegate, both objects would be owning each other. This, of course, is a retain cycle, similar to a leak with the same consequence (objects that should be dead remain alive).
Other times, the objects are peers: neither one owns the other, probably because they are both owned by the same third object.
Either way, the object with the delegate should not retain its delegate.
(There's at least one exception, by the way. I don't remember what it was, and I don't think there was a good reason for it.)
Addendum (added 2012-05-19): Under ARC, you should use weak instead of assign. Weak references get set to nil automatically when the object dies, eliminating the possibility that the delegating object will end up sending messages to the dead delegate.
If you're staying away from ARC for some reason, at least change assign properties that point to objects to unsafe_unretained, which make explicit that this is an unretained but non-zeroing reference to an object.
assign remains appropriate for non-object values under both ARC and MRC.
Note that when you have a delegate that's assign, it makes it very important to always set that delegate value to nil whenever the object is going to be deallocated - so an object should always be careful to nil out delegate references in dealloc if it has not done so elsewhere.
One of the reason behind that is to avoid retain cycles.
Just to avoid the scenario where A and B both object reference each other and none of them is released from memory.
Acutally assign is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates.

How to know if an object is autoreleased or not?

I'm getting a a bit annoyed about some objects being autoreleased without me knowing. It's probably a good thing that they are, but if they are, I want to know. The documentation doesn't say which methods autorelease objects, so I usually test my way forward, which in my opinion is silly. For example, [NSDate date] autoreleases the object, and so does [NSArray arrayWithObjects:...]. How do you know without the documentation telling you?
I'm starting to see a pattern though that methods like these, the ones that create objects with a static function, always returns the autoreleased object. Is this always true?
Basically, if you init, copy, or retain an object you are responsible for releasing it. If you don't, you are not responsible for releasing it.
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html
Many classes provide methods of the
form +className... that you can use to
obtain a new instance of the class.
Often referred to as “convenience
constructors”, these methods create a
new instance of the class, initialize
it, and return it for you to use.
Although you might think you are
responsible for releasing objects
created in this manner, that is not
the case according to the ownership
policy set out earlier. Because the
class creates the new object, it is
responsible for disposing of the new
object.
The method signature itself tells you. The pattern to methods with signatures like "classNameWithData:data1:data2" is to return an alloc/init/autorelease instance of that thing. They are conveniences there so that you don't have to do it.
If you do not want an autorelease version of something, then do not instantiate them that way, and use the proper alloc/init, and release when you are done. This method is much more explicit, and a bit more error prone because if an exception is thrown your release block could get missed, but that is the price you pay for having it that way.