Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView ivar vs. tagging a local UIView var

Scenario 1: For a UIViewController, is it better to (1) create an ivar for a UIView that I access again in 1 or 2 functions outside of loadView? Or, (2) should I just tag it in loadView and then use - (UIView *)viewWithTag:(NSInteger)tag to access it again in the other functions? I'm guessing that option 1 increases the memory by the size of a pointer, so 32/64-bits, and creates accessor methods (assuming I declare @property & @synthesize), and then requires releasing the ivar in dealloc and setting it to nil in viewDidUnload... and that option 2 saves memory, has less setup code, but costs some processing time and a little extra code to find the view by its tag. Am I right about all this?

In this scenario, it feels best to use an ivar, but I'm not sure.

Scenario 2: What about for a custom subclass of UIView that has 5 subviews? Bearing in mind that I'll have about 30 instances of this custom subclass in memory at a given time (They'll be subviews of tableViewCells.), should I use 5 ivars for the subviews, or should I tag them all?

In this scenario, I'm thinking the memory saved by tagging them all would be worth the small performance hit of searching for them with - (UIView *)viewWithTag:(NSInteger)tag.

Thoughts?

Thanks!

Matt

like image 681
ma11hew28 Avatar asked Dec 10 '22 13:12

ma11hew28


1 Answers

Considering that difference in memory usage is negligible (unless you're going to have 100 of these views, in which case you might want to look into how you can reuse some of those views), you should probably consider what would make your code more readable and maintainable. I personally think that using an ivar would be more readable, but it's also possible that for your particular case using tags would be more readable.

When writing code, I always try to think about the person who's going to reading the code a year or two years from now. That person might be me, or it might be someone else, but either way, I know that person will appreciate readable code. They're less likely to thank me for saving 1k of memory on a device that has at least 128 MB of RAM.

like image 88
Jacques Avatar answered Dec 25 '22 06:12

Jacques