Memory issue for global variable and class variable on iPhone/iPad/iPod touch - iphone

When we should use global variable and when class variable and why?
I hope your experiences and ideas to share with us who are novice in this platform.
Example:
Let, i need to trace timestamp and position of touch events (eg. touch start, end) on a layer. I can trace it using global variable or class variable of the class which implements touch event. What should I do?
Regards,
-Sadat

This isn't a problem specific to Objective C or the iPad family of devices.
Variables should have the minimum "visibility" and "duration" that they need, and no more.
You would have to come up with some very convincing reasons for trying to get a global variable through our code review processes. They're almost always able to be replaced with something a little more appropriate.
In response to your comment:
I don't know how global/class variable affects on memory.
There's a nice snippet over here which details how to do class level variables. These are normal C file-scoped variables so they're not visible outside the file but you only get one for the class, not one for every object that you instantiate.
In that sense, they have the advantages of a global (minimal storage and the value is still accessible for reading) without the disadvantages (polluting the global name-space and making it possible for code outside of the class to change it).
And, if it doesn't need to be read outside of the file, just don't provide the initCount method.

It's kind of a flip answer, but don't use global variables at all - stick with class methods and expected encapsulation. Anything else and you'll be fighting the cocoa libraries from dusk to dawn. If you follow their patterns, which include class methods, encapsulation, delegation, etc - you'll be making huge headway with relatively little effort.
The only place where I might think to call something a "global variable" in my efforts are project-wide constants - so not variables at all, but sometimes there's a good need for a constant across your project (TableViewCell identifiers comes to mind)

Related

pass by refernce method in matlab

I'm developing a robotics application in Matlab for my thesis. I'm experienced in C#, PHP, js, etc etc.
I would love if objects I create could somehow be passed by reference. I heard that there are things called "handle objects" and others called "value objects". I can't find any specific documentation on how to create a "handle object" and it seems they are usually graphics objects.
I have a few design patterns that are easy to implement when passing by reference is possible. I would like certain objects to share 'simulation spaces', without making each space a global variable. I would like to avoid passing IDs around everywhere, in an effort to keep objects synchronized. I would like to share environmental objects between robots, without worrying about the fact that passing this object actually copies it. (this will lead to bugs over time)
I'm starting to feel like my only solution will be to have a weird global 'object broker' that has the latest copy of many common system objects. I hope to avoid this sort of thing!
Any advice would be amazing!
Handle objects are created by the following syntax
classdef myClass < handle
properties
% properties here
end
methods
% methods here
end
end
A good place to start looking in the documentation is the classes start page. Note that value and handle classes have only been implemented in R2008a, and are reasonably bug-free since R2009a (though more recent releases have improved performance quite a bit).
If you're coming from other languages, this section about the differences between Matlab and other languages OOP can be useful.
Your classes should inherit from the handle abstract class
classdef MyHandleClass < handle
% // class stuff
Class with this semantics can be passed by reference in a java like way.
Consider also this section of the guide.

How do you organize your UI design variables, objects, etc. in iOS?

As the iPad app I am making has been growing its size, it is hard for me to keep track of UI design values. Here, I am talking about values such as a table's width, background colors, and a title's font.
I would like to organize all UI design-related values and objects more efficiently.
How do you organize these?
Do you #define values in a header file?
Do you declare them as global variables or not?
Do you put your values one static class?
Or do you think not-organizing these values is rather better?
I would like to hear your advice.
Thank you :)
Yes it depends, therefore just some rules of thumb...
Do you #define values in a header file?
...in cases where I might want to change this locally only, eg for constants, colors, alignments, button images, ... the main reason why I do this however is the documentation it allows by giving the local defines a long explaining name
Do you declare them as global variables or not?
...an all my apps I have a MainDataManager Class, that holds all the variables I need globally - for the UI part often I have my own globally used object. This is extremely useful, simplifies the code, and probably one of the most important things I learned early on. might also see here Using Variable of AppDelegate as a Global Variable - question regarding release/retain
Do you put your values one static class?
...static classes exist kind of conceptually. Static variables are quite useful when you want to give a method some kind of memory of its own. However, none plays an important role in my UI.
In general, I like to use IB to layout the screens but set all the button names, labels, texts in the code. Why? Because when I have to localize the app maintaining multiple XIB files (for each language there will be one isolated XIB file to maintain) becomes a real burden even if there is only one single change in the layout.
All the global constant settings are always kept in GloblDefinitions.h while at the same time I have in my .pch file this entry #import "GlobalDefinitions.h"
So the combintation of a delegate variable provided globally + GlobalDefinitions.h for constants is my solution.
Its a good question. When combining use of interface builder with hand-coded UI tweaks and/or custom components you also have the problem of duplicated values between IB and code.
In some situations, for readability and for easy adjustment by a third party its easier if values are just hard coded in-place - so in trival cases (e.g. cases where the value is not repeated anywhere else or is unlikely to change) this might be a valid option.
In general, if the constants are specific to the layout of a particular UI component then it seems to make sense to #define them in the header file for the UI component that uses them - I think putting them all in one global file breaks the decoupling that you'd like to have between user interface components, and also for readability it can be easier for another dev to find them in the header file.
On the other hand if there are values that are used consistently across multiple UI components within the one application, then these can be defined in a global include file. Similarly if there are 'base' values that are used to derive other lengths etc. that are used commonly across multiple UI components these also can be stored in a global include.
Also whereever possible make use of the layout manager margin flexibility settings and width/height flexibility settings to minimise the need to hard code values. And when relevant, derive values from a base value or a system value (e.g. screen width).
At the end of the day if the value is there in code in front of you sometimes that much easier to figure out and tweak than changing a #define off in some other file - on the other hand - if the same value is repeated in multiple places and a #define is not used, then it can be very confusing for another coder to come in and change one of these repeated values only and try to understand and sift through the resultant side effects and which other places the value should be changed.
Well Ryan that depends upon you..
You can either use pre processor directives..
declaring in .pch file.
or you can either make an object class taking all the constants....
Hope that will help you..
Thanks
This is what I have learnt from few of my previous projects.
1] Naming conventions - use appropriate and standardized prefix. ex tblRecordLis, viewControlPanel etc.
2] Keep Constants together - keeping all constants at one place reduces the pain of searching entire project to find/fix/replace constants and their values.
3] Grouping relevant Classes together according to utility and their functionality.
4] UI constants like size, offsets , frame values (Which you need to hard code) can be kept in constants
a few which I used are
#define MenuPopoverFrame CGSizeMake(278, 550);
#define LandscapeContentSize #"{{0,0},{719,734}}"
#define PortraitContentSize #"{{2,0},{765,980}}"
5] Using IB as much as possible as it gives us more flexibility.
6] PROPER commenting and documentation proves to be a life saver when dealing with debugging.
I find it easy to declare keys as constants as using them at multiple places also increases the chances of error if used as such. eq key named #"method" can be better declared as
#define kMethodKey #"method"
This very simple thing saves my time while debugging when the project size grows larger.
** Taking hints from Apple's samples also gives you a great help in keeping your code standardized.

What functions to put inside a class

If I have a function (say messUp that does not need to access any private variables of a class (say room), should I write the function inside the class like room.messUp() or outside of it like messUp(room)? It seems the second version reads better to me.
There's a tradeoff involved here. Using a member function lets you:
Override the implementation in derived classes, so that messing up a kitchen could involve trashing the cupboards even if no cupboards are available in a generic room.
Decide that you need to access private variables later on, without having to refactor all the code that uses the function.
Make the function part of an interface, so that a piece of code may require that its argument be mess-up-able.
Using an external function lets you:
Make that function generic, so that you may apply it to rooms, warehouses and oil rigs equally (if they provide the member functions required for messing up).
Keep the class signature small, so that creating mock versions for unit testing (or different implementations) becomes easier.
Change the class implementation without having to examine the code for that function.
There's no real way to have your cake and eat it too, so you have to make choices. A common OO decision is to make everything a method (unless clearly idiotic) and sacrifice the three latter points, but that doesn't mean you should do it in all situations.
Any behaviour of a class of objects should be written as an instance method.
So room.messUp() is the OO way to do this.
Whether messUp has to access any private members of the class or not, is irrelevant, the fact that it's a behaviour of the room, suggests that it's an instance method, as would be cleanUp or paint, etc...
Ignoring which language, I think my first question is if messUp is related to any other functions. If you have a group of related functions, I would tend to stick them in a class.
If they don't access any class variables then you can make them static. This way, they can be called without needing to create an instance of the class.
Beyond that, I would look to the language. In some languages, every function must be a method of some class.
In the end, I don't think it makes a big difference. OOP is simply a way to help organize your application's data and logic. If you embrace it, then you would choose room.messUp() over messUp(room).
i base myself on "C++ Coding Standards: 101 Rules, Guidelines, And Best Practices" by Sutter and Alexandrescu, and also Bob Martin's SOLID. I agree with them on this point of course ;-).
If the message/function doesnt interract so much with your class, you should make it a standard ordinary function taking your class object as argument.
You should not polute your class with behaviours that are not intimately related to it.
This is to repect the Single Responsibility Principle: Your class should remain simple, aiming at the most precise goal.
However, if you think your message/function is intimately related to your object guts, then you should include it as a member function of your class.

iPhone -- context parameters vs. global variables

In my iPhone development, I've always used global variables for lots of stuff. The style guide in my new job says we should use context parameters instead. So I need to figure out what that means and how to do that.
Can anyone explain in more detail what this means -- or point me to some code that works this way?
Thanks
It sounds like there may be a clash in nomenclature. From this definition of Context Parameters, they seem to be concerned storing global state for the duration of a session. Perhaps, you could use a 'contextParameters' NSDictionary within NSUserDefaults to store your globals. To the extent that your globals might need to be exported in their entirety (for debugging, for state saving) this might be useful in the long run.
The style guide might just be generically saying to keep your variables scoped based on the context of their usage. For example if you have a variable that you need for the lifetime of a class instance then make it a member variable of that class. If it is something that you need for the lifetime of the app then put it in an application wide object (but not a global variable).
If you use a global object (which could mostly be a big C struct containing all your former global variables) instead of individual naked global variables, you might be able to copy the object, serialize it to save it or create a unified core dump, eventually add setters/listeners, etc.
If you break the global object up, based on the shared scope or the required context of groupings of instance/struct variables, then the fractional objects might end up being good candidates for the M portion of an MVC repartitioning of your code for better reuse, extensibility, etc.

What's better: Writing functions, or writing methods? What costs more performance?

Currently I am making some decisions for my first objective-c API. Nothing big, just a little help for myself to get things done faster in the future.
After reading a few hours about different patterns like making categories, singletons, and so on, I came accross something that I like because it seems easy to maintain for me. I'm making a set of useful functions, that can be useful everywhere.
So what I did is:
1) I created two new files (.h, .m), and gave the "class" a name: SLUtilsMath, SLUtilsGraphics, SLUtilsSound, and so on. I think of that as kind of "namespace", so all those things will always be called SLUtils******. I added all of them into a Group SL, which contains a subgroup SLUtils.
2) Then I just put my functions signatures in the .h file, and the implementations of the functions in the .m file. And guess what: It works!! I'm happy with it, and it's easy to use. The only nasty thing about it is, that I have to include the appropriate header every time I need it. But that's okay, since that's normal. I could include it in the header prefix pch file, though.
But then, I went to toilet and a ghost came out there, saying: "Hey! Isn't it better to make real methods, instead of functions? Shouldn't you make class methods, so that you have to call a method rather than a function? Isn't that much cooler and doesn't it have a better performance?" Well, for readability I prefer the functions. On the other hand they don't have this kind of "named parameters" like methods, a.f.a.i.k..
So what would you prefer in that case?
Of course I dont want to allocate an object before using a useful method or function. That would be harrying.
Maybe the toilet ghost was right. There IS a cooler way. Well, for me, personally, this is great:
MYNAMESPACECoolMath.h
#import <Foundation/Foundation.h>
#interface MYNAMESPACECoolMath : NSObject {
}
+ (float)randomizeValue:(float)value byPercent:(float)percent;
+ (float)calculateHorizontalGravity:(CGPoint)p1 andPoint:(CGPoint)p2;
// and some more
#end
Then in code, I would just import that MYNAMESPACECoolMath.h and just call:
CGFloat myValue = [MYNAMESPACECoolMath randomizeValue:10.0f byPercent:5.0f];
with no nasty instantiation, initialization, allocation, what ever. For me that pattern looks like a static method in java, which is pretty nice and easy to use.
The advantage over a function, is, as far as I noticed, the better readability in code. When looking at a CGRectMake(10.0f, 42.5f, 44.2f, 99.11f) you'll may have to look up what those parameters stand for, if you're not so familiar with it. But when you have a method call with "named" parameters, then you see immediately what the parameter is.
I think I missed the point what makes a big difference to a singleton class when it comes to simple useful methods / functions that can be needed everywhere. Making special kind of random values don't belong to anything, it's global. Like grass. Like trees. Like air. Everyone needs it.
Performance-wise, a static method in a static class compile to almost the same thing as a function.
Any real performance hits you'd incur would be in object instantiation, which you said you'd want to avoid, so that should not be an issue.
As far as preference or readability, there is a trend to use static methods more than necessary because people are viewing Obj-C is an "OO-only" language, like Java or C#. In that paradigm, (almost) everything must belong to a class, so class methods are the norm. In fact, they may even call them functions. The two terms are interchangeable there. However, this is purely convention. Convention may even be too strong of a word. There is absolutely nothing wrong with using functions in their place and it is probably more appropriate if there are no class members (even static ones) that are needed to assist in the processing of those methods/functions.
The problem with your approach is the "util" nature of it. Almost anything with the word "util" it in suggests that you have created a dumping ground for things you don't know where to fit into your object model. That probably means that your object model is not in alignment with your problem space.
Rather than working out how to package up utility functions, you should be thinking about what model objects these functions should be acting upon and then put them on those classes (creating the classes if needed).
To Josh's point, while there is nothing wrong with functions in ObjC, it is a very strongly object-oriented language, based directly on the grand-daddy of object-oriented languages, Smalltalk. You should not abandon the OOP patterns lightly; they are the heart of Cocoa.
I create private helper functions all the time, and I create public convenience functions for some objects (NSLocalizedString() is a good example of this). But if you're creating public utility functions that aren't front-ends to methods, you should be rethinking your patterns. And the first warning sign is the desire to put the word "util" in a file name.
EDIT
Based on the particular methods you added to your question, what you should be looking at are Categories. For instance, +randomizeValue:byPercent: is a perfectly good NSNumber category:
// NSNumber+SLExtensions.h
- (double)randomizeByPercent:(CGFloat)percent;
+ (double)randomDoubleNear:(CGFloat)percent byPercent:(double)number;
+ (NSNumber *)randomNumberNear:(CGFloat)percent byPercent:(double)number;
// Some other file that wants to use this
#import "NSNumber+SLExtensions.h"
randomDouble = [aNumber randomizeByPercent:5.0];
randomDouble = [NSNumber randomDoubleNear:5.0 byPercent:7.0];
If you get a lot of these, then you may want to split them up into categories like NSNumber+Random. Doing it with Categories makes it transparently part of the existing object model, though, rather than creating classes whose only purpose is to work on other objects.
You can use a singleton instance instead if you want to avoid instantiating a bunch of utility objects.
There's nothing wrong with using plain C functions, though. Just know that you won't be able to pass them around using #selector for things like performSelectorOnMainThread.
When it comes to performance of methods vs. functions, Mike Ash has some great numbers in his post "Performance Comparisons of Common Operations". Objective-C message send operations are extremely fast, so much so that you'd have to have a really tight computational loop to even see the difference. I think that using functions vs. methods in your approach will come down to the stylistic design issues that others have described.
Optimise the system, not the function calls.
Implement what is easiest to understand and then when the whole system works, profile it and speed up what's slow. I doubt very much that the objective-c runtime overhead of a static class is going to matter one bit to your whole app.