Tutorial :Iterate attributes and IBOutlets of a UIViewController



Question:

I've a generic UIViewController on my app. All the UIViewController on the app inherits from this generic one.

I'm trying to automate the deallocation and releasing of attributes and IBOutlets as properties.

I'm doing the first (attributes) on dealloc method and the second (IBOutlets as properties) on viewDidUnload.

- (void) dealloc {    [_att1 release];    _att1 = nil;      [_att2 release];    _att2 = nil;      // ...  }    - (void) viewDidUnload {     self.att1 = nil; // att1 is an IBOutlet     self.att2 = nil; // att2 is an IBOutlet       // ...  }  

Is there any way to iterate all my attributes and IBOutlets to simplify this operations? I want to avoid do it for each outlet and attribute and delegate it to the generic UIViewController.

Thanks.


Solution:1

I'm not sure this is possible. Further, I'm not sure it's a good idea.

First, why it's not possible: The IBOutlet keyword is solely for the benefit of Interface Builder. IB scans the source code (or some XCode-internal indexing of the source code) to identify the IBOutlets available in a class. I don't believe there is any distinction between IBOutlet and regular property in the compiled code. So, even if you find a list of attributes or properties, you won't be able to distinguish between those for -[UIView viewDidUnload] as opposed to dealloc.

Second, why it's not a good idea. Memory management is complex in Objective-C. The tools in Instruments can also help determine where excess memory is being allocated and the Clang static analyzer (Cmd-Shift-A in XCode) can help you find potential memory leaks from unreleased or inappropriately retained objects. Any introspection-based release automation system is certain to confuse the static analyzer, to say nothing of the other developers on your team.

It's a noble effort to try to automate such an error-prone task as memory management, but I think you may be better off sticking with the existing tools and waiting for the garbage collector to find its way to the iPhone instead.


Solution:2

If they are really just named attr1, attr2, attr3... than you can.

Use key-value-coding

For example:

for(int i = 1; i <= numberOfAttributes; ++i) {        [self setValue: nil forKey: [NSString stringWithFormat: @"%@%i", @"attr", i]];      [[self valueForKey: [NSString stringWithFormat: @"%@%i", @"attr", i] release];  }  

note that you have to set numberOfAttributes yourself.


But if you can't keep track of the nubmer of attributes or there are to many, you should think about using an array to gather them


Solution:3

Try to get all the IBOutlets using [self.view subviews] and browse the array to delete them.

For the attributes, I'm still looking...


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »