Schrodingrrr
Schrodingrrr

Reputation: 4271

Any advantage of using 'self.view.frame.size.height', over storing it in a variable instead?

Suppose, an app has a view controller with a plethora of views inside, whose frames are relative to the view controller's frame. Is there any advantage/disadvantage of using self.view.frame.size.height/width, over storing their values in variables, and using them instead ?? Advantages/disadvantages in terms of memory usage, CPU usage, time-delay, et cetera. And, in the core of it, are these values of height, width, or related parameters stored in memory somewhere, or are they fetched/calculated every time the code requests them ??

Upvotes: 1

Views: 3467

Answers (3)

Bryan Chen
Bryan Chen

Reputation: 46598

I just want to point out that self.view.frame.size.height = 1 will not work as many expected. It is same as CGRect temp = self.view.frame; temp.size.height = 1;

So always separate setter/getter call and structure accessors in different line. i.e.

CGRect frame = self.view.frame; // use objc dot syntax to get frame
frame.size.height = 100;   // use C struct accessors 
self.view.frame = frame;  // use dot syntax to set frame

Upvotes: 0

CodenameLambda1
CodenameLambda1

Reputation: 1299

Advantages:

  1. When views are resized, the width and height variable automatically gets updated with resized values. Storing local variables for width and height will make you write unncecessary code to manage the updation of both on each possible event causing the view to resize.

  2. With your local variable a duplicate will increase in memory. Though the magnitude of memory waste is negligible, there is some extra memory used to hold your duplicate variable is always a fact.

Disadvantages:

  1. If you refer the width and height from the view.frame.size.height itself, then you may loose the initial value.

Upvotes: 0

Midhun MP
Midhun MP

Reputation: 107141

I'll suggest storing the value in a variable and using that will be better.

If you call self.view.frame.size.height it will be calculated each time. They'll affect the performance.

doing:

int counter = self.view.frame.size.width;
for(int loop=0;loop<counter;loop++)
{
}

is better than:

for(int loop=0;loop<self.view.frame.size.width;loop++)
{
}

In certain scenarios, if the width and height is changing dynamically(animation logic), and you need to do something based on the values then using self.view.frame.size.width will be a good thing.

Upvotes: 1

Related Questions