Categories
iOS & ObjectiveC Iphone Developer Technological

ObjC Programming

The basics of Objective C programming for iOS apps by Marcio Valenzuela Santiapps.com
The basics of Objective C programming for iOS apps

The Big Picture

ObjC is OOP which means objects send messages to other objects. Before getting into messages, let’s define objects.

Objects.
This is very diverse. An object can be a string, a number, a Boolean, an integer, an array, a dictionary or even one you create yourself. There are any types of objects but let’s start at the root object.

The root object is called NSObject. You’ll see references to it in code but you’ll hardly ever use it directly. This is called the root object because it’s the starting point of any object. It’s like Adam and Eve rolled into one and ANY other kind of object in ObjC comes from it. An NSObject is defined as an object that takes un space in memory and that’s about it. Because any object will take up space, right? Now think of NSObject as sitting at the top of a family tree and all it’s descendants come from that point and thus share it’s traits, which is to say, any object takes up space.

Now we can think of objects as those already created for us and those we create. Objects created for us are such as NSString where we can ‘store’ text, NSNumbers where we can store numbers, NSDate for dates, NSArray for a sort of list of objects, NSDictionary for a sort of dictionary list where a key (word) has one corresponding value (definition), UIButton for buttons, UILabels for text labels, UIImageViews for images,UIWebViews for HTML pages, UIView for views and UIViewControllers for view controllers.

The first pre-made objects mentioned up to NSDictionary, can be thought of abstract objects. The next few objects I mentioned from UIButtons to UIViewControllers can be thought of more concrete and visible objects because you can actually see those objects in the resulting program or app. As you can see they have the prefix UI which refers to UserInterface whereas NS stands for NeXTSTEP.

Just to clear up the last few objects, an iOS app has 1 window. That one window usually has 1 UIView and every UIView requires a UIViewController which basically controls what happens in that view and how the user can interact with it.

So those are 2 categories of pre-made objects; abstract ones and concrete ones that basically have a graphical representation at runtime.

Now there are the objects we create ourselves. If I’m working on a Contacts app, I will probably create a special object to handle all the information related to a contact. What I will usually do is subclass (or use a more basic but the most related object) to create a foundation for my contact object. NSObject is the most basic object so I will subclass NSObject and add the things I think I might add to NSObject to best represent my info needs. So I might add a few NSStrings to hold first and last names as well as company and perhaps nickname. I might add NSNumbers to hold phone numbers, an NSArray of NSStrings for emails and so on. In the end, my Contact object would be based on NSObject but would represent a unique kind of object which I would call Contact instead of NSObject.

If on the other hand I needed to create an object that had more in common with a button than with an NSObject, I would subclass UIButton. If my object needed to be more like a special text label, I would subclass UILabel.

Ok so once I have all the objects I need, I need those objects to send messages. Objects need to send messages to communicate and they need to communicate in order to carry out tasks. Let’s call those messages methods. And let’s think of an object sending a message by calling a method. So for example, pre-made objects have pre-made methods in order to send pre-made messages.

For example; NSString has a pre-made method called capitalizedString. So how does it work? Well the format is:

[object methodName];

This calls the method called “methodName” on the object called “object”. We say that we are sending the “methodName” message to the “object” object. It just so happens that if your object is the hello world string:

object = @”hello world”;

Then the result of that message would be:

HELLO WORLD

So how do we know what objects there are and what their methods are?

Apple developed the OS and has its documentation. It’s pretty cool because it’s OOP so there is a manual for every object and here is the one for NSString:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

It has a lot of methods because it’s a very basic object. Ok so that’s a look at a pre-made abstract object. You can look at others such as NSArray and you’ll see it has methods consistent with things you might expect to do with a list, such as count which returns the number of objects in a list or addObject which adds a new item to a list and so on.

If you take a look at the pre-made concrete objects such as UIButton:

https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html

you’ll see methods like titleForState: which will set the button’s title for a particular state (selected or not). You will also notice some things called properties. Those are things like the button’s tintColor or enabled.

Ok, so what does it all mean Basil?

Well in an app, you are given a main window. You can add objects to that window such as a UIView and a UIViewController. The UIView may have a backgroundColor set to blue and a certain size. You may also want to tell that view that when the view loads, it should present a UIAlertView, which are those pop up views you see in iOS apps, that reads “Welcome user!”. To do that you need to add a special object called UIViewController. Then you might want to add a UITextField for the user to enter a code and a UIButton for the user to tap on once he/she is done to check if the code is correct. The code might be stored in an NSString object in order to check of its valid.

So how you do all this? In each object’s corresponding Class file set. Each object has a class file set consisting of an interface (.h) and an implementation(.m) file. The interface typically defines that object’s properties and methods whereas the .m file has the implementation of each method. So the .m contains the bull of the code.

A typical class file set might look like this:

@interface MyContact : NSObject

@property (nonatomic,strong) NSString *firstName;
@property (nonatomic,strong) NSString *lastName;
@property (nonatomic,strong) NSString *email;
@property (nonatomic,strong) NSArray *phoneNumbersArray;

-(void)callContact;

-(NSArray*)listOfNumbers;

@end

And then in the .m you might have:

@implementation MyContact

-(void)callContact{
//some code to bring up the Phone app and pass it the main phone number}

-(NSArray*)listOfNumbers{
//return the list of all this contact’s phone numbers
return phoneNumbersArray;
}

To make an app you would need to create a view with its viewcontroller and add a MyContact class to create contacts and combine messages from the viewcontroller class to the MyContacts class and vice versa in order to make the app interact with the user.

Categories
Iphone Developer Technological

GrandCentralDispatch & Blocks

Grand Central Dispatch iOS
Grand Central Dispatch iOS Santiapps.com by Marcio Valenzuela

GCD helps improve your apps performance and responsiveness by outsourcing processes that require a lot or computing power to the background while keeping your UI responsive.  Normally you might want to do some heavy lifting.

Let’s create an Empty Application.  You need to declare a IBOutlet UIImageView *imageView ivar in your appDelegate, make it a property and synthesize it in .m and make the connection in Interface Builder, IB.  In it’s viewDidLoad method put the following code:

// Download the image
NSURL *url = [NSURL URLWithString:@”http://www.santiapps.com/assets/bbkoko.jpg”];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLResponse *res = [[NSURLResponse alloc] init];
NSError *err = nil;
NSData *data = nil;
data = [NSURLConnection sendSynchronousRequest:req
returningResponse:&res
error:&err];
// Convert the data to a UIImage
UIImage *image = [UIImage imageWithData:data];

// Scale the image
UIImage *thumbImage = nil;
CGSize newSize = CGSizeMake(90, (90 / image.size.width) * image.size.height);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
thumbImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Add this to a UIImageView
self.imageView.image = thumbImage;

If you load this up, you’ll notice it’ll take quite some time to load.  Analyzing this code you notice that the heaviest workload is the NSURL request. Ideally we would like to dispatch this to a separate queue so that the app doesn’t stall while this is happening. BTW, the best way to see how a task like this stalls your app’s launch is to place the code right into your applicationDidFinishLaunching, which will stall the display of the MainWindow.xib.

Run the code as is and you’ll notice how the app hangs on the black screen before displaying the default white colored MainWindow.xib background.

So what we want to do is throw this out into a side queue so as to not hold up the presenting of the UI of the app. Grand Central Dispatch, or GCD for short, is ideal for this. First add this line to your AppDelegate, or whatever the class you are using it in:

#import <dispatch/dispatch.h>

Then fix your code to implement GCD:

dispatch_queue_t downloadQueue = dispatch_queue_create(“imageDL”, NULL);
dispatch_async(downloadQueue, ^{

NSURL *url = [NSURL URLWithString:@”http://www.santiapps.com/assets/bbkoko.jpg”];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLResponse *res = [[NSURLResponse alloc] init];
NSError *err = nil;
NSData *data = nil;
data = [NSURLConnection sendSynchronousRequest:req
returningResponse:&res
error:&err];
     dispatch_async(dispatch_get_main_queue(), ^{

// Convert the data to a UIImage
UIImage *image = [UIImage imageWithData:data];

// Scale the image
UIImage *thumbImage = nil;
CGSize newSize = CGSizeMake(90, (90 / image.size.width) * image.size.height);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
thumbImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Add this to a UIImageView
self.imageView.image = thumbImage;

});

});

dispatch_release(downloadQueue);

Run it now and notice how fast the MainWindow.xib pops up on the screen and later displays the image once it has downloaded.

If you want to get a more live view of how GCD works, try this code out in an app:

Simple Block Time Example
           

             NSDate *date = [NSDate date];

void (^now)(void) = ^ {

NSLog(@”The date and time is %@”, date);
};

now();
date = [NSDate date];
sleep(5);

now();

You should see in your console the time logging every 5 seconds.

GCD is very helpful for sending off queues that take a long time (like web fetches – images or db queries – image processing etc).  Your app is still usable while the heavy work is done on another thread that doesn’t obstruct your main thread which is where UIKit stuff used by the user, is handled.

Categories
Iphone Developer Technological

How to Read iOS or Mac OS Programming Documentation

The toughest part for me to get started was reading the Apple Documentation on iOS or MacOS. When I got into more APIs it got more complex. You need to understand how to read API or proprietary code documents in order to understand how to create a piece of code, connect to web services or debug changes in code.

You will very often see the term DEPRECATED, which means a particular method name is no longer used. This is very important so let’s take a look at Apple Docs first:

NSArray Class Reference
Santiapps. Marcio Valenzuela. Learn to program for iOS or MacOS

This tells us that the object of type NSArray has many methods that you can call on it. They may be Instance or Class methods but they are all listed here. If you want to know what an object can do, you ask it for its type and come to the Class Reference site.

Notice there are many tasks you can call on an NSArray:

5. NSArray Class Reference
Santiapps. Marcio Valenzuela. Learn to program for iOS or MacOS. Understand how to read NSArray Class Reference.

Notice the task with red text next to it that reads “Deprecated in…”. Like I said it says it was deprecated after a certain version of the OS. Now let’s suppose we want to know about a particular method we can use on this type of object, let’s look at initWithObjects, it only sounds natural that if we want to create an array, we would like to put objects in it:

6. NSArray Example
Santiapps. Marcio Valenzuela. Learn to program for iOS or MacOS. Understand how to read NSArray Class Reference.

This means that if you call our standard way of creating any object:

Object Class *objectPointer = Object Class alloc …

and then we insert that method signature -(id)initWithObjects:(id)firstObject…

we get this:

Object Class *objectPointer = Object Class alloc -(id)initWithObjects:(id)firstObject

we can start putting objects into our array object. Now let’s look at the correctly formatted code:

NSArray *myArray = [[NSArray alloc] initWithObjects:@”hi”, @”bye”, nil];

Notice we took out the -(id) at the beginning of the method signature because this forcibly has to return an NSArray object. And the reason we can add this method signature to the NSArray *myArray creation line is because we know that NSArray contains that method signature inside its Class file. We can make sure of this by using the Jump To Definition in Xcode!

Let’s do so for an example I just ran across. I had been working on a game using Cocos2d. This means I was using an API or library or third party code framework. These terms are usually interchangeable but they basically mean the same. When somebody or some company works on a bunch of code that helps you perform certain tasks. For example, Cocos2d creators worked on many Classes to create Cocos2d. One such class is CCAnimation which takes in frames and strings them together to create an animation. They recently released v.2.0 and this particular class changed some of its method signatures to include improvements I guess.

If I open my code in Xcode and try to run my old code, it crashes saying “Unrecognized Selector sent to instance”.

1. XCode Console debugging
Santiapps. Marcio Valenzuela. Learn to program for iOS or MacOS. Understand how to read NSArray Class Reference.

This means that instance of CCAnimation doesn’t recognize that old method or selector. Presumbale because they changed the old name to accommodate new structural changes. So I right click over the CCAnimation call in my code where the app crashed:

CCAnimation Definition
Santiapps. Marcio Valenzuela. Learn to program for iOS or MacOS. Understand how to read NSArray Class Reference.

And when I Jump To Definition I will be taken to that Class Reference for that Class:

3. CCAnimation Definition
Santiapps. Marcio Valenzuela. Learn to program for iOS or MacOS. Understand how to read NSArray Class Reference.

This gives me the Class Reference for CCAnimation, the one being used in my project, and tells me which methods the Class now implements. Now I just find the method which more closely matches my needs.

It’s important to learn how to go from a crash to the documentation which can help you fix that crash.