Re: Does setFormatter() retain?
Re: Does setFormatter() retain?
- Subject: Re: Does setFormatter() retain?
- From: Wim Lewis <email@hidden>
- Date: Wed, 24 Aug 2016 13:41:36 -0700
On Aug 24, 2016, at 1:04 PM, Andreas Falkenhahn <email@hidden> wrote:
> I have read Apple's memory management guide on retain/release and
> I think I've basically got it, but there's just one thing that
> I'm not confident about and that is "setXXX" methods which accept an
> NSObject parameter and I don't know how I can know whether the
> "setXXX" retains or not.
In general, if a method you call wants to keep a reference to an object you pass in, it is that method's responsibility to retain it (or copy it, or whatever). If it doesn't hold on to the formatter, then it won't retain it. The goal of reference-counting, whether ARC or not, is that all that information can be safely considered an implementation detail of the method you call, and not something you need to worry about.
Delegate and data source setters are an unusual, exceptional case: an object with a delegate typically doesn't retain its delegate, just keeps a reference to it. This is dangerous, since the delegate can get deallocated, leaving a dangling pointer (--> soon you'll crash). If the API conventions were being formed today, delegates would probably be 'weak' pointers, but since they predate the existence of weak pointers they get the "slightly dodgy poor-man's weak pointer" behavior of simply not retaining. Why is this? It's to avoid retain-cycles, since very often, an object's delegate is its (direct or indirect) owner in a conceptual sense and therefore already retains the object.
> Post-scriptum: Yes, I know, there's now ARC and everything and
> all those retain stuff shouldn't be used anymore
ARC just automatically inserts the same retain/release calls that you would have written manually. (Plus some optimizations on top of that, but that's the basic idea.) It can be useful to understand MRR even if you don't write it.
On Aug 24, 2016, at 1:24 PM, Andreas Falkenhahn <email@hidden> wrote:
> If it retains, I could just do the following:
>
> [textField setFormatter:formatter];
> [formatter release];
>
> And I wouldn't have to worry about "formatter" any longer.
Yes, you can do exactly that. If the textField needs the formatter to continue to exist after -setFormatter: returns, it will retain it. It's the textField's job to worry about that retain/release, not yours. You only need to retain objects that *you* have a reason to reference in the future.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden