1
votes

Please note, I am not using Interface Builder.

I have made my subViews __weak so that they are automatically zero'd on iOS 5 with ARC when they the objects they reference are deallocated. This means I don't have to zero them manually in viewDidUnload (which seems the safest pattern to adopt).

However because they are weak I cannot directly assign them to my ivars when I alloc them, or ARC immediately releases them, the only solution I have found is assigning to a temporary strong local variable like so:

UIView *strongTmp = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:strongTmp];
weakIVar = strongtmp;

This is ugly and its purpose is not immediately obvious without a verbose comment. I want something (more) elegant like:

[self.view addSubview:weakIVar = [[UIView alloc] initWithFrame:self.view.bounds]];

But this generates the same compiler warning (the object will be released immediately after assignment).

Any suggestions? Thanks in advance.

2
Hey Brad/Max, have you found an answer to this problem? I just ran into having to do this in a few places and it is indeed quite ugly and annoying. - SaamJB

2 Answers

1
votes

The 'assign to local variable" technique is totally normal. Just get used to it, or use a nib.

0
votes

One (non-ideal) solution is to add a class-level initializer on a relevant category, this effectively tells ARC to return an auto-released version of your thing, here an example with a UIView:

@implementation UIView (mxcl)
+ (id)viewWithFrame:(CGRect)frame {
    return [[self alloc] initWithFrame:frame];
}
@end

weakIVar = [UIView viewWithFrame:self.view.bounds];
[self.view addSubview:weakIVar];

NOTE: you can call this on any UIView subclass, provided that subclass's designated initializer is still initWithFrame.

Note, I believe I tested this a few months ago, but have not tested the above code explicitly, please comment if the example above needs amendment.