Saturday, July 8, 2017

How to: Basic of XCode Methods & Functions in Objective-C

Why ObjC?

Cause we're oldskool! :D


When we start to code, what we need to do is write methods on top of the already available delegates (namely the View Lifecycles delegates like viewDidLoad or viewDidLayoutSubviews). A typical method that we quickly create is IBActions. These are automatically created when you drag an outlet in Storyboard to your header file.

-(IBAction)aButtonWasClicked:(id)sender {
  // your button was clicked by user

The aButtonWasClicked: is the name of the method. Note that I include the semicolon at the end. This indicates there is a parameter to be supplied to the method. So if you want to call this method elsewhere programatically, you need to write:

[self aButtonWasClicked:obj];

If you don't know what is obj, and sender is never used in the method, you can supply nil to it:

[self aButtonWasClicked:nil];

And if you want to supply it to a @selector() you do it this way:

@selector(aButtonWasClicked:) // semicolon is important

If you know what sender is (in this case, obviously a UIButton), you can make use of it by using TYPECASTING. Typecast is basically implying a certain type to a generic/unknown object. For example:

-(IBAction)aButtonWasClicked:(id)sender {
   UIButton *button = (UIButton*)sender; // this is typecasting of the sender obj which is type "id" to "UIButton"
   // now you can use button object properties.
   [button setTitle:"I was Clicked!" forState:UIControlStateNormal];

Okay. Now on to writing your own method - which is the cool part!. There are quite a few types of methods, but the most common ones are instance method and class method. Instance methods are the ones started with a dash "-". And class methods are the ones started with a plus "+".


Instance methods are called by... drumroll... an instance of the object. Most instance methods are normally called by the viewController in which they contain, which is "self", hence we see [self... at the front.

Instance methods are most common, and there are a few variations of it. The most common that I use is like below:

-(void)setColorForView:(UIColor*)color andSize:(CGSize)size {


Lets break this method down. "-" indicates it is an instance method. The thing in bracket is the return value of this method. void means nothing. So you will get nil returned by this method if you call it by assignment. For example:

id value = [self setColorForView:clr andSize:size];

// value here will be nil always.

Next, setColorForView: is the NAME of the method AND it also acts as a selector name for the first parameter. andSize is the selector name for the next parameter. You can add to the method as much as you want. But be practical. Such method as below is ridiculous to say the least.

-(void)setColorForView:(UIColor*)color andSize:(CGSize)size andHeight:(CGFloat)height 
withFlag:(int)flag andViewController:(UIViewController*)viewCtrl 
andYourMom:(UIMom*)mom isFat:(UIFat*)fat {
 // crazy!


Then you ask, what if I want to pass many parameters into the method? Well, you can simplify it by adding your parameters into NSDictionary and simply use:

-(void)setColorForView:(NSDictionary*)params {
   // get color: [params objectForKey:@"Color"];

Or, best way is to create a custom object with all the parameters and pass that instead of dictionary.

-(void)setColorForView:(MyParams*)params {
 // get color: params.color;

Better and cleaner method name right?

What if you want your method to return a value? Remember the void? Now just replace that with a type that you want to return. For example lets make the method return a Boolean:

-(BOOL)setColorForView:(UIColor*)color andSize:(CGSize)size {
 if (size.width>100)
   return YES; 
   return NO; 

Do you want to be fancy? a simple if/else statement can be reduced to a one-liner like this:

-(BOOL)setColorForView:(UIColor*)color andSize:(CGSize)size {
  return (size.width>0)?YES:NO; // woaaahh mindblown!

The method checks for size.width if it is over 100, the method returns YES, and if not returns NO. You can use this method like below:

BOOL widthOverHundred = [self setColorForView:color andSize:size];
// widthOverHundred now will be YES or NO depending on size value.

You can also return an OBJECT from instance method. For example:

-(UIColor*)getColorForView:(int)tag { 
  if (tag==0) return [UIColor redColor]; 
  else return [UIColor greenColor]; 

Note that an Object type name includes * to indicate a pointer to the object.

What if you want to return many values and objects??? Hopefully you've guessed it, just use NSDictionary or custom object.

-(NSDictionary*)getParamsForView:(int)tag {
    NSDictionary *dict =// construct dictionary here
    return dict;

-(MyParams*)getParamsForView:(int)tag {
    MyParams *params =// construct params here
    return params;

That's about all there is to know about instance methods, for noobs like us. Pretty easy peasy lemon squeezy.

Class methods are similar, but implementation is different. I seldom use it except some special cases. A real world example of Class Method is

[NSString stringWithFormat:@"%d",val];

"stringWithFormat:" is the class method. As you can see, we can use it immediately using its class and there is no need for us to create an "instance" of the class before we use it.

Typically a class method is created in custom class. Or when you create a category of an existing class.

Consider a custom class called Vehicle.

With class methods we can init a particular vehicle with different types and the correct seatCapacity.

-(id)init {
 self = [super init];
 if (self) {
 // any default init setup
 return self;

+(id)createCar {
  self = [self init];
  self.seatCapacity = 5.0;
  return self;
+(id)createBus { 
  self = [self init];
  self.seatCapacity = 20.0; 
  return self; 

To use it:

Vehicle *car = [Vehicle createCar];
Vehicle *bus = [Vehicle createBus];

Pretty cool eh?

Another useful type of Class method is the completion block (which I love very much). It is exactly like having an office boy who does errands for you XD and returns to you when the job is done. Completion block is extremely useful when you want to execute something that takes time, for example, downloading or uploading data. For example, here's a class completion block method to download an image file.

+(void)downloadImageWithURL:(NSString *)urlString
          completedWithData:(void(^)(NSData *data))completedWithData
                    failure:(void(^)(NSString *errorMessage))failure

    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableCharacterSet *chars = NSCharacterSet.URLQueryAllowedCharacterSet.mutableCopy;
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:chars]];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url
                                completionHandler:^(NSData *data,
                                                    NSURLResponse *response,
                                                    NSError *error) {
                                    if ((error==NULL)&&([data length]>0)) {
                                    } else {
    [task resume];


Put this in your custom class, say, "DownloadManager", then in your ViewController.h import DownloadManager.h and then you can you it in your ViewController.m like so:

[DownloadManager downloadImageWithURL:@"" completedWithData:^(NSData *data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.myImage.image = [UIImage imageWithData:data];
    }failure:^(NSString *errorMsg) {
        NSLog(@"ERROR: %@",errorMsg);

This is particularly useful when you want to have an asynchronous image downloader to be used with your TableView or CollectionView. Sure, the class method is not complete, for example, you should also add a way to save the downloaded images into a "cache" of some sort if you are using it with TableView/CollectionView. But here, I just want to demonstrate the Class block method.

So that's all there is to it as a basic introduction to Objective-C methods for iOS. I'll add more if I remember anything that I missed out. Meanwhile, comment below if you have any opinions. Thank you for reading!

Friday, April 28, 2017

How To: Seriously Plan and Design an iOS Apps or Games

Hey whatsapp? (see what I did there? XD)

All these while we've been playing with XCode and making fun things without much care of how our app's structure looks like.

The thing about making an app/software, there are so many ways to do one thing. So many ways to code a feature. But if you are serious in making apps, you need to consider your app carefully and thoroughly, so that updating the app won't be a pain in the a$$ in the future. This is more so, when making your own app, or an app for a customer that may be requested to be updated in the future. The overall structure and back bone of the app needs to be as good and as organized as possible. Otherwise you'll end up crazy, trying to make sense of things in the app or when you want to add a new feature to the app.

So what you should do? I now will outline the necessary steps and points for you to consider when making an app.


This is perhaps the first most important part of designing an app. Wireframing is basically a sketch of how an app/game going to look like and how it will work. Page per page. It is best to go as detail as possible. For example, how many views it will have, and how does each view interact with each other. And also, what kind of animations, menus, confirmation dialogs, to have. What's important to note when designing the wireframe, you need to consider any views that can be REUSED, and those should be created once and the small variations therein be controlled by a property in that view. This is to prevent having multiple views that are very similar, and having similar codes in both views. It doubles or triple your job really - when you update on one view, you also need to do the same on another view. This is bad for you! Programmers must be lazy, and so he must create views as efficient as he can.

Anyway, here is an example of a wireframe of my app Blur.Depth that I made with an A4 paper.

There are plenty aspects of wireframing. For example position of buttons, controls, labels, are all important. You need to imagine a user using your app when you design it. Tab bars and toolbars normally are located at the bottom. This is because it is closest to user's thumb when a person uses a smartphone. It is safe to assume everyone is right handed (XD), so design your controls with that in mind. See the area where the thumb can reach.The top bar can also have controls, but should be minimized and not a control that user going to be using frequently.

In addition to the wireframing, you need to choose COLORS! Yes, colors play important role in your app. Normally you could choose a theme color. A color is important for people to recognize your app by. A clear example of this is Twitter and Facebook. Yes they both already chose and sticking with their color theme. Twitter a light blue. And Facebook a dark blue. It is not a must though. Some apps don't even have a theme color. But they use a certain shade of any color and it can work nicely. See below:

This is where your art skill going to shine. If you don't know art, you can learn like how I did. I chose Inkscape and learn how to create shapes and then made all my app's graphics assets. If not, you need to hire a graphics designer to do this for you.

To add, there are multiple tools out there to do wireframing. Even lets you run the prototype in your device. That way you can experience how your app is going to feel before actually start designing it. It is always good to have that chance. Decisions made at this time is crucial to how the app going to look and feel like at the end.


Before you start to create a project, you need to decide which language you are going to code the app with. As of right now, Swift should be your choice. I started with Objective-C and are now well versed in it in my own style of coding, so I haven't made a single app on Swift (XD Im sure ill regret it later). And also choose if you are going to use XCode (Apple's official app IDE) or others (Xamarin, PhoneGap, etc). Xamarin uses C# (C-Sharp). Some even uses HTML/XML. AND, there are also app maker that don't even require you to code at all (but pretty limited what they can do). For me I always prefer native, but if you want to develop once for multi platform, then you can consider others. Game is much easier to make multiplatform than apps because game doesn't normally need platform specific controls. Once you decide that, then you can start creating a project.


Before I work with a company as an app developer, I never used source control. As such my source codes are stored locally in my machine. (Not smart, actually very dumb really). I make a backup copy once in a while into my iCloud. But many times I have experienced where I changed the code too much over a day and not happy with its direction. There is no way to undo this (Ctrl-Z dont work because I have saved it and close the project during lunch). The copy in the iCloud's progress was too far away back. Had no choice but to undo manually. So many times wasted there!

Source control deals with these kinds of issue superbly. The only problem is that for source control service to be private, you need to pay for it. Free ones like github or bitbucket, exposes your sources to all, but I'm not really sure I might be wrong. I haven't searched for a free private source control hub, but if you find any, feel free to share in the comment section. Or if you have your own server, you could setup a free source control service hub on your own server.

Source control is also great when you have multiple people working on the same project (but  of different modules - because having multiple people working on same module will give you merging headaches :D good luck with that shit hahaha). If you don't understand what Source Control is, in simple terms

Source Control is basically a multiple copies of your project stored at different times. Basically everytime you "commit" a project, a copy of it is added to the server together with a date-timestamp. And you can move between each commits by just double clicking the commits in its timeline and instantly your project in your machine will be updated to those copies. You can also have "branches" where a project splits into two (or more) so each branch is handled by a single developer working on different module of the app. These "branches" then can be merged upon completion.

There are free software to handle source sontrol such as SourceTree, or even GitHub has its own software too.


I find that using CocoaPods is always best if you use native solution. Even when you don't use any library that they offer, it readies the app for future library usage. There are plenty of cool libraries in cocoaPods! For me, at most I use the admob cocoapods, because most of other objects I normally create myself (subclassing). But still it is nice to have a centralized location of library you use, so that you don't have to keep on downloading it when a new version is released. And some of the library you simply almost need to use an opensource one that are well made and used by many, for example the websocket library, SocketRocket.


If you decide on XCode, then you SHOULD REALLY use Storyboards! I know, I was a stubborn noob back then, sticking to xibs. But storyboards make your navigation between views much easier. So so much easier. And whether you use storyboards or not, you should also use AutoLayout with constraints. Constraints may look hard at first but it is actually very easy once you understand the concept. It is also much superior than the old ResizingMask.


Now comes the personal part. Coding decisions and styles. The thing that turned me off totally when working as an App Developer is dealing with other people's codes in existing apps. I didn't come from a Software background, so I have not experienced any of this before. I can't handle it.


I find it is so hard to deal with other people's code. Perhaps because I have a little bit of OCD? Or am I a control freak? XD. Most of the time I felt like it's faster for me to just remake the whole app. Gives me so much stress to modify something or to add a feature to codes I can't make sense of. I think, other developers will have a headache reading my code too XD. You surely have your own styles, but to me it is important to ORGANIZE and always REFACTOR anywhere you can. If you are working in a team, it is probably best that you assign each module to a single developer, and only he will touch those modules. Anyway here is how my style of coding is:

A. I must have an AppConstants.h header in the app. 

All the constants should be centralized here. Don't use AppDelegate or any of your singletons to store the constants. Among the constants that I store normally are color themes, server URL, and any static strings that I use like Error messages, dictionary keys, userdefaults keys, segueIdentifiers and so on. There shouldn't be any hardcoded values anywhere else. So when you want to change static values, you just open AppConstants.h and it's all there, and you change once and effective everywhere! Makes your job easy and not messy.

B. I have a common methods class. 

I also have a common methods class, where any methods that are going to be used (or foreseen to be used) by many viewcontrollers are written. Examples of such methods are:

-function to make a view (or any of its subclasses) rounded. (layer.cornerRadius).
-check internet connections
-resize a UIImage
-QRCode generator
-save an image to documents folder (both png or jpg).
-save an image to tmp folder (png or jpg)
-load an image from documents folder
-load an image from tmp folder

C. I use delegates and avoid overusing the NSNotificationCenter and UserDefaults. 

Delegates are a great way to interacting between two or more viewcontrollers. I just learnt about delegates last year (2016) and I am wondering why didn't I learn about this sooner. NSNotifications, while it works, it doesn't have a destination. It's like a guy shouting on a mountain, hoping someone in the town nearby hears it. Some people use userdefaults to keep on writing/reading data between viewcontrollers. This works, too, but... reading and writing causes extra battery usage. You want to make people use least power when they're using your app. And.... I know many devs will cry "Singletons are bad and evil", but for me Singleton is the best ever thing I learnt in programming. And let me quote a cocos2dx developer:

I use a single singleton, and frankly ignore the 'singletons are bad' cry-babies.

D. I try to keep with the MVC pattern.

Back in the early days, I don't really understand MVC. Probably still don't. But the idea of MVC that I get now make sense. You have to separate codes within their confinement. A model code should remain in model, the view code remain in view, and controller code remain in controller. A good example of this is when creating a UITableView. Your views, of course are the storyboard. The model is the datasource of the table, normally a NSArray or NSMutableArray. The controller is the tableview delegates. To make this follow MVC, you don't define the model in cellForRow (while that can work). What you do is define the model outside of the delegate (ie, you setup the data in viewDidload or other place), then you code the controller (cellForRow) to read the model only. This way, each MVC stays in their boundaries.

E. I organize my Project Navigator and arrange Storyboards nicely. 

In the left panel of XCode there is a Project Navigator. It helps me to organize this. I create folders for each scenes. If you use libraries, then have a folder called "Library" and drag all of them there. Don't leave them all over the places. Organized Project Navigator allows me to find a class easily and quickly.

F. I use Meaningful Names !!! 

Name everything meaningfully. Early this year I went to an iOS app developer interview just to see how valuable my app developing experience is. The company owner himself interviewed me. After completing a coding task, he commented quite a few things on my code and I agree with him completely. One of it was about the Project class naming. I left the default ViewController.m/h as it is... while it should've been renamed as MainViewController or something meaningful related to the Scene it represents.

Even variable names must make sense. Having a BOOL named "yesOrNo" is useless to the code reader (which could be yourself in 2 years). Long variable names are okay if it is needed to explain about itself. Something like _isWifiConnectionAvailable is totally good to me.

And last but not least, you should also give meaningful names to your graphics assets or any other assets that you use (video, mp3, wav etc). anIcon.png is about as descriptive as "I shit thru my a-hole". XD.


This is also important aspect of the app planning. What would you like to do with the app in the future? Most definitely you are going to need to update it. There is not buts in this. What additional features do you have planned for version 1.1, 1.2, etc? And do you want to offer additional features or are you going to just update according to latest iOS and focus on user experience?

Many apps developers adopt the "add feature" mindset to an app updates, which I oppose full-heartedly. As such, a small app with sufficient features, suddenly become this monster of a beast that is so ugly and it can transform to Optimus Prime and also make your coffee hahaha! But an app or software is not supposed to do everything. An app or software is actually supposed to do what it is designed to do, in the most efficient, and beautiful manner, with least bugs (hey we all must admit zero bugs is impossible).

So while developing, have in mind of the future updates you'd like to do. If you want to add features to a scene, make sure the control you choose for the scene now is able to cope with the additional feature in the future.


After reading all the above, you should now have an idea how you should approach about making an app or game. With good planning and design and preparation, your app is going to be noticed by many people and people will love using it and don't even mind paying 99cents for it. Good luck!

Sunday, February 26, 2017

How To: Create Undo and Redo in a Drawing App

Hi guys.

I want to share how to create undo and redo in a drawing app. I tried using NSUndoManager for this, but it doesn't work. Why? I don't know. When something don't work, I tried for a bit, and if I have no more idea to try and work it out, I simply abandon the idea and try something else totally. There is no point lingering on something that you simply do not know.

The way to implement undo and redo is quite simple really. You just detect user's end stroke, and then save that drawn image into a MutableArray. This will eat memory a bit especially if you have a very big image. Alternatively you can simply store the drawn image in the TMP folder of your app sandbox use names like "undo0.png, undo1.png, undo2.png...". Have a global undo index variable to keep track of the undo/redo steps. When undoing, you -1 to the index, and load the image based on this index number. And when redoing, you +1 to the index, and load that image.

Something like this:

-(void)undo {
undoIndex -= 1;
NSString *imageName = [NSString stringWithFormat:@"%undold.png",undoIndex];
yourImage.image =  [self loadImageFromTMP:imageName];

-(void)redo {
undoIndex += 1;
NSString *imageName = [NSString stringWithFormat:@"%undold.png",undoIndex];
yourImage.image =  [self loadImageFromTMP:imageName];

Of course, you have to handle the undoIndex limits (>=0 and <maxUndolevel). Simple right? Kthxbai.