Archive for the ‘iPhone’ Category

Swift 3.1: Swift Package Manager – Part 2

In last part of Swift 3.1 release, we discussed the major language changes, but Swift Package Manager was one of the most awaited updates. This update would have a major impact on your code as it has many new functionalities.

Image result for swift 3.1 Now, let us talk about why Swift Package Manager Updates was most awaited?

Every modern programming language has an official dependency management system. They come with an official solution for code distribution as an example RubyGems for Ruby, Composer for PHP, NPM for NodeJS, etc. But iOS used to be different, developers had to rely on third-party dependency management tools like CocoaPods and Carthage until Swift Package Manager came. Image result for swift 3.1

Also Read: How Swift 3.1 is different from earlier version? – Part 1

Now Swift Package Manager is an official replacement for CocoaPods and Carthage. And you should be definitely using it in Swift project because-

  • It is an official package manager for Swift. It is considered to be a trusted source of the Swift packages.
  • CocoaPods and Carthage have Pros and Cons as they are managed by open-source communities, but SPM is managed by Apple. So there are fewer chances of having trouble, the developers don’t have to rely on open-source communities.
  • Though it is a major product and is still in development phase, but it will definitely grow. As it is the future, so you should consider using it as dependency manager.
  • Swift is a server side language, so SPM is expected to work on both Linux and macOS. There will be no restriction of using macOS to build and distribute Swift packages.

What is new?

1. Editable Packages

Swift 3.1 added editable packages concept in Swift Package Manager. It edits command by taking an existing package and converting it to an editable one. The editable package replaces all the canonical package’s occurrences in dependency graph. ‘–end-edit’ command can be used to revert the package manager back to canonical resolved package.

2. Version Pinning

Another amazing concept is added in Swift 3.1- version pinning package. The version pin command pins one or all dependencies like this-
$ swift package pin –all      // pins all the dependencies $ swift package pin Foo        // pins Foo at current resolved version $ swift package pin Foo –version 1.2.3  // pins Foo at 1.2.3
The developer can use the unpin command to revert to the previous package version with following commands-
$ swift package unpin —all $ swift package unpin Foo
The package manager stores the active version pin information from package.pins. If the file doesn’t exist, it creates an automatic file based on the requirements (as a part of automatic pinning process) specified in the package manifest. Image result for swift 3.1

3. Other Bits

The reset command of swift package resets a package back completely. There will be no dependencies checked out or built artifacts present after resetting them. And the swift test — parallel command executes tests in parallel.

4. Multiple Return Functions

The new package has disable the C functions which return twice such as vfork and setjmp. They change the control flow of the program. So the swift community is no longer supporting them, and using them results in compile-time error.

5. Disabled Auto-Linking

THE SPM has also disabled the auto-linking feature of module maps for C language targets-
  1. // Swift 3.0
  2. module MyCLib {
  3.    header “foo.h”
  4.    link “MyCLib”
  5.    export *
  6. }
  1. // Swift 3.1
  2. module MyCLib {
  3.    header “foo.h”
  4.    export *
  5. }

Also Read:Kotlin- The Next-Gen Android App Development Language

What next?

Swift 3.1 is a polished version of swift 3.0 with many new features. But as the technology changes and advances every single day, we can expect many more serious changes in Swift 4.0 later. These changes could include improvement in generics, regular expression, ergonomic string design, etc.  

How Swift 3.1 is different from earlier version? – Part 1

As most of the developers know that Swift is a general-purpose programming language. It is built using a modern approach to safety, performance, and software design patterns. And if you are already an iOS developer, you are already familiar with these things! Recently, a beta version of Xcode 8.3 and Swift 3.1 was released with Swift Package Manager features and improvements to the language. In this article we will majorly discuss about the Language improvements, rest will be covered in other part of the article. Let us check out the most significant features and changes in Swift 3.1 as it will have a major impact on your code!

Also Read:Swift 3.1: Swift Package Manager – Part 2


Swift 3.1 has downward compatibility, a person can work on lower versions codes of Swift. All you need to do is to migrate your project to Swift 3.0 using Edit\Convert\To Current Swift Syntax in Xcode. Start Xcode, select File-> New-> Playground. Choose iOS as the platform, you can call it whatever you want, and save it wherever you want.

Language Improvements

There are a number of languages improvements in this release. It includes failable initializers for numeric types, new sequence functions, and more. Let us check them out-

1. Failable Numeric Conversion Initializers

The new version implements failable initializers for all numeric types such as Int, UInt, Float, Double, etc. It either completes successfully without losing any information or simply returns NIL. This feature helps while dealing with loosely typed data conversion from external sources in a safe and recoverable manner. Just check it out by processing this JSON code-
  1. class Student {
  2.  let name: String
  3.  let grade: Int
  5.  init?(json: [String: Any]) {
  6.    guard let name = json[“name”] as? String,
  7.          let gradeString = json[“grade”] as? String,
  8.          let gradeDouble = Double(gradeString),
  9.          let grade = Int(exactly: gradeDouble)  // <– 3.1 feature here
  10.    else {
  11.        return nil
  12.    }
  13. = name
  14.    self.grade = grade
  15.  }
  16. }
  17. func makeStudents(with data: Data) -> [Student] {
  18.  guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
  19.        let jsonArray = json as? [[String: Any]] else {
  20.    return []
  21.  }
  22.  return jsonArray.flatMap(Student.init)
  23. }
  1. let rawStudents = “[{\”name\”:\”Ray\”, \”grade\”:\”5.0\”}, {\”name\”:\”Matt\”, \”grade\”:\”6\”},
  2.                    {\”name\”:\”Chris\”, \”grade\”:\”6.33\”}, {\”name\”:\”Cosmin\”, \”grade\”:\”7\”},
  3.                    {\”name\”:\”Steven\”, \”grade\”:\”7.5\”}]”
  4. let data = .utf8)!
  5. let students = makeStudents(with: data)
  6. dump(students) // [(name: “Ray”, grade: 5), (name: “Matt”, grade: 6), (name: “Cosmin”, grade: 7)]
Here, failable initializer is used to convert the grade property from Double to Int inside the Student class.
let grade = Int(exactly: gradeDouble)
If gradeDouble is a fractional value, it will fail. It will succeed only if the value can be represented exactly as an integer.

Also Read:Kotlin- The Next-Gen Android App Development Language

2. New Sequence Functions

There are two new functions for data filtering to the standard library’s Sequence protocol- prefix(while:) and drop(while:). Consider the Fibonacci infinite sequence:
  1. let fibonacci = sequence(state: (0, 1)) {
  2.  (state: inout (Int, Int)) -> Int? in
  3.  defer {state = (state.1, state.0 + state.1)}
  4.  return state.0
  5. }
  Swift 3.0 simply specify the iteration count to iterate through the Fibonacci sequence-
  1. // Swift 3.0
  2. for number in fibonacci.prefix(10) {
  3.  print(number)  // 0 1 1 2 3 5 8 13 21 34
  4. }
Swift 3.1 lets you use prefic(while:) and drop(while:) with a condition to get all the elements of the sequence between two given values.
  1. // Swift 3.1
  2. let interval = fibonacci.prefix(while: {$0 < 1000}).drop(while: {$0 < 100})
  3. for element in interval {
  4.  print(element) // 144 233 377 610 987
  5. }
In the code, prefix(while:) returns the longest sub-sequence which satisfies a certain predicate. while drop(while:) does the opposite.  

3. Concrete Constrained Extensions

Swift 3.1 extended generic type with a concrete type constraint. Previously, it could not extend a type like this due to protocol constraint. Example- Ruby on Rails provides isBlank method for checking for user input. Let us check out how it would be implemented in Swift 3.0 as a computed property on the String data type extension:
  1. // Swift 3.0
  2. extension String {
  3.  var isBlank: Bool {
  4.    return trimmingCharacters(in: .whitespaces).isEmpty
  5.  }
  6. }
  7. let abc = ” “
  8. let def = “x”
  9. abc.isBlank // true
  10. def.isBlank // false
If you want the isBlank computed property to work with optional strings as well, you would do the following in Swift 3.0:
  1. // Swift 3.0
  2. protocol StringProvider {
  3.  var string: String {get}
  4. }
  5. extension String: StringProvider {
  6.  var string: String {
  7.    return self
  8.  }
  9. }
  10. extension Optional where Wrapped: StringProvider {
  11.  var isBlank: Bool {
  12.    return self?.string.isBlank ?? true
  13.  }
  14. }
  15. let foo: String? = nil
  16. let bar: String? = ”  “
  17. let baz: String? = “x”
  18. foo.isBlank // true
  19. bar.isBlank // true
  20. baz.isBlank // false
Swift 3.1 lets you extend a concrete type instead of a protocol like this:
  1. // Swift 3.1
  2. extension Optional where Wrapped == String {
  3.  var isBlank: Bool {
  4.    return self?.isBlank ?? true
  5.  }
  6. }
It is better than earlier versions because it does the same work in fewer lines.

4. Nested Generics

The new version allows you to mix nested types with generics. Understanding it with an example would be easier when an article is posted on a website, the actual coding behind looks like this-
  1. class Team<T> {
  2.  enum TeamType {
  3.    case swift
  4.    case iOS
  5.    case macOS
  6.  }
  8.  class BlogPost<T> {
  9.    enum BlogPostType {
  10.      case tutorial
  11.      case article
  12.    }
  14.    let title: T
  15.    let type: BlogPostType
  16.    let category: TeamType
  17.    let publishDate: Date
  19.    init(title: T, type: BlogPostType, category: TeamType, publishDate: Date) {
  20.      self.title = title
  21.      self.type = type
  22.      self.category = category
  23.      self.publishDate = publishDate
  24.    }
  25.  }
  27.  let type: TeamType
  28.  let author: T
  29.  let teamLead: T
  30.  let blogPost: BlogPost<T>
  32.  init(type: TeamType, author: T, teamLead: T, blogPost: BlogPost<T>) {
  33.    self.type = type
  34. = author
  35.    self.teamLead = teamLead
  36.    self.blogPost = blogPost
  37.  }
  38. }
  We nest BlogPost inner class within Team outer class and make both classes generic. And this is how it looks like-
  1. Team(type: .swift, author: “Cosmin Pupăză”, teamLead: “Ray Fix”,
  2.     blogPost: Team.BlogPost(title: “Pattern Matching”, type: .tutorial,
  3.     category: .swift, publishDate: Date()))
  4. Team(type: .swift, author: “Cosmin Pupăză”, teamLead: “Ray Fix”,
  5.     blogPost: Team.BlogPost(title: “What’s New in Swift 3.1?”, type: .article,
  6.     category: .swift, publishDate: Date()))
  Whereas it could be simplified. Nested inner type can inherit the parent’s class type by default if the nested inner type uses the generic outer one. Therefore you don’t have to declare it, like so:
  1. class Team<T> {
  2.  // original code
  4.  class BlogPost {
  5.    // original code
  6.  }  
  8.  // original code
  9.  let blogPost: BlogPost
  11.  init(type: TeamType, author: T, teamLead: T, blogPost: BlogPost) {
  12.    // original code   
  13.  }
  14. }

5. Convert Non-Escaping Closures to Escaping Ones

In Swift 3.0, closure arguments were made non-escaping to function by default, while you can convert non-escaping closures to escaping ones temporarily by using withoutActuallyEscaping() helper function in Swift 3.1. Let us understand this with an example-
  1. func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void,
  2.             on queue: DispatchQueue) {
  3.  withoutActuallyEscaping(f) { escapableF in     // 1
  4.    withoutActuallyEscaping(g) { escapableG in
  5.      queue.async(execute: escapableF)           // 2
  6.      queue.async(execute: escapableG)     
  7.      queue.sync(flags: .barrier) {}             // 3
  8.    }                                            // 4
  9.  }
  10. }
This function runs two closures simultaneously and then returns when both are done.
  1. f and g come in as non-escaping and are converted to escapableF and escapableG.
  2. async(execute:) calls require escaping closures. Fortunately, you have those because of the previous step.
  3. By running sync(flags: .barrier), you ensure that the async(execute:) methods are completely done and the closures won’t be called later on.
  4. Scope limits the use of escapableF and escapableG.
If you squirrel either temporary escaping closures away (i.e. actually escaped them) it would be a bug. There are many other changes in Swift 3.1. They include Swift Package Manager Updates, Multiple-Return Functions, Disable Auto-Linking, etc. We will be discussing it in next part. Till then share your views with use!  

Integrating Google oAuth APIs with iPhone Applications

This blog is an effort to round up on how to consume Google’s REST APIs in an iPhone App.  As usual with RESTful APIs, the client specifies an action using an HTTP verb such as POST, GET, PUT, or DELETE and the resource by a globally-unique URI of the following form: The response will be returned by the API in JSON format. The APIs use OAuth 2.0 protocol for authentication and authorization. Google supports several OAuth 2.0 flows that cover common web server, JavaScript, device, installed application, and server to server scenarios. Here we are dealing with installed application on device scenario. Steps to integrate the Google APIs in a normal iOS application are not different than the normal OAuth flow. Register Application: First of all , the application must be registered through Google API console. The result of this registration process is a set of values that are known to both Google and application (e.g. client_id, client_secret, redirect_uri, etc.). The set of values generated varies based on the type of application you are building. Another thing that you need to do is to turn on the APIs that your application needs to access in API Console. Obtain an Access Token from the Google Authorization Server: This is the normal OAuth flow where we need to get the access token to call an API. For authorization call this url, it will show a gmail login window which needs user login credentials:
Parameters Value
response_type code
client_id the client_id obtained from the APIs Console.
redirect_uri the redirect_uri values registered at the APIs Console.
scope space delimited set of permissions the application requests.
state anything
In iPhone, application can fetch authorization code from following code:
NSString *tokenCode
   = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('title')[0].innerHTML;"];
Authorization code will be something like “token = tokenValue”. Retrieve the tokenValue and use that to obtain an access token from Google by shooting the post request to following url.
<pre><em id="__mceDel">NSString *url = @"";
NSString  *data =[NSString stringWithFormat: @"code=%@&",token];
Response of above url will return the dictionary having token, expire time, refresh token and token type. { “access_token”:”1/fFAGRNJru1FTz70BzhT3Zg”, “expires_in”:<expiry_time>, “token_type”:”Bearer”, “refresh_token”:”1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI” } After obtaining access token above, you are ready to call the Google API for your purpose. Calling Google Api: After application has obtained an access token, application can access a Google API by including it in either an access_token query parameter or an Authorization: Bearer HTTP header. Application can call on those api which are passed as scope in authorization URL. For example, a call to theCalendar API using the access_token query string parameter looks like this: This will return entries on the user’s calendar list. Similarly you can call any other API from the API console which requires an OAuth Token. Enjoy building the cool apps that integrate with Google API !!

iOS 6 Smart App Banners

With the release of iOS 6, Apple introduced a new way of promoting your apps. The feature is called Smart App Banners and it can be seen in Safari browser of your iOS 6 device.
  • As you can see, the app banner will be visible at the top of the webpage by pushing the whole page down a little, so this improves the browsing experience as compared to other promotional methods where adds are shown as full page display or as a pop-up window.
  • Tapping the banner will move you to the app itself or app in the app-store depending upon whether you have that app installed on your device or not.
  • Implementing the Smart app banner is very easy, just you need to add a meta tag of the following type in the head section of the page on which you want to show this banner :-
    <meta name="apple-itunes-app" content="app-id=myAppStoreID, affiliate-data=myAffiliateData, app-argument=myURL">
  • content attribute of this meta tag have 3 parameters (1 compulsory + 2 optional) which are:-
  • app-id (required) :- The itunes id of your app.
  • affiliate-data (optional) :- The itunes string of the affiliate. Affiliates are the persons who earn some part of money as commission, if that app is bought by some client.
  • app-argument (optional) :- The url on which the app will open & jump if it is already installed on your device. Basically it provides a contextual navigation to your app.
  • Here are some quick examples of the meta tag :-
  • <meta name="apple-itunes-app" content="app-id=13456789">
    <meta name="apple-itunes-app" content="app-id=123456789, affiliate-data=partnerId=123&siteId=123456">
    <meta name="apple-itunes-app" content="app-id=123456789, app-argument=http://abcd/1159">
Enjoy the seamless promotional banners for your application !!

Getting HTML elements value from UIWebView

Recently, we came across a problem where we had to fetch some html values from UIWebView. The blog lists source code for extracting a few common elements from UIWebView. The instance method stringByEvaluatingJavaScriptFromString of UIWebView comes in hefty to find such a value.This function will grab the current HTML contents of the view using the Document Object Model, parse the Javascript, then give it to you as an NSString of HTML. Examples To get string from the title of the HTML page:
NSString *currentURL = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('title')[0].innerHTML;"];
To get string from class name:
NSString *someHTML = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('class name')[0].innerHTML;"];
To get string from element id:
NSString *html = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('div id').textContent=''"];
theWebView – UIWebView object on which html page is loaded. This approach comes in pretty handy when you want minimal user interaction in some browser savvy process(such as openauth authentication) and hence resulting in a better User Experience. Enjoy the UIWebView awesomeness !!

Implementing Local Notifications in iPhone Applications

Integrating push notifications with iPhone has been really tricky before iOS4.0. You needed to have a dedicated server to push notifications to the applications. However with iOS4.0, Apple introduce the concept of local notificatiions. Local Notifications are a new way to send “push notifications” to your app without having a dedicated server and associated server side coding. Local notifications can be scheduled on the user’s device to fire at any given time; you can even set them to be recurring.The primary purpose of local notifications is to provide a mechanism for a suspended or background application to gain the attention of the user. For example, an audio streaming app might need to notify the user about the loss of network connection or a calendar based application an approaching appointment. The blog details about the coding of delivering a local notification on an iOS device. How To use Local Notification To have iOS deliver a local notification at a later time, an application creates a UILocalNotification object, assigns it a delivery date and time, specifies presentation details, and schedules it. However, make sure you are implementing application:didreceiveLocalNotification in your app delegate if you want to see the notification while your app is in the foreground. Scheduling Notifications
- (IBAction) scheduleAlarm:(id) sender
    [eventText resignFirstResponder];

    // Get the current date
    NSDate *pickerDate = [NSDate date];

    // Break the date up into components
    NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
    NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit )
    // Set up the fire time
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:[dateComponents day]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]]; // Notification will fire in one minute
    [dateComps setMinute:[timeComponents minute]];

    NSDate *itemDate = [calendar dateFromComponents:dateComps];
    [dateComps release];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
    localNotif.fireDate = itemDate;// this sets when notification will be called.
    // Notification details
    localNotif.alertBody = [eventText text];// this shows the alert box with message.
    // Set the action button

    localNotif.alertAction = @"View";
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = 1;
    // Specify custom data for the notification

    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
    localNotif.userInfo = infoDict;
    // Schedule the notification
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];
In this example we set the notification to the text that the user entered into the text field. InfoDict dictionary is our chance to associate some additional information with the alert. When a local notification is triggered, the option is available to play a sound to gain the user’s attention. If such an audio alert is required the corresponding sound file must be added to the application project resources and must be in Linear PCM, MA4 (IMA/ADPCM), uLaw or aLaw format. If no sound file is specified, the default is for the notification to be silent (though the iPhone device will still vibrate). Handling Notifications After They Fire The last thing is to determine what to do when a notification fires. This step is handled inside of the appDelegate. When a notification fires, there are one of two situations. 1. The app is running and 2. The app is not running (or running in the “background”) . Open up your app delegate .m file and add the following code.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  // Override point for customization after application launch.
  // Add the view controller's view to the window and display.

    [window addSubview:viewController.view];
    [window makeKeyAndVisible];

  // Handle launching from a notification

    UILocalNotification *localNotif =[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotif) {
        NSLog(@"Recieved Notification %@",localNotif);
    return YES;
    -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
  // shows badge value on tab bar
       NSString *badgeValue = [NSString stringWithFormat:@"%d",notifyCount];
       [[[[[self tabBarontroller] tabBar] items] objectAtIndex:2] setBadgeValue:badgeValue];

  //  setting badge value of tab bar as shown below.
       application.applicationIconBadgeNumber = 0;
The method is invoked when a running application receives a local notification. In this method, we create a string named badgeValue,which contains an integer value from notifyCount variable. We set this badgeValue in the tab bar item which is present at index no 02, which is meetings tab in the provided screenshot.

SQLite Datbase connectivity in iPhone Applications

Database integration is often required in case we want to store some sort of persistent information in the application. The other prominent usage is caching the data for example caching the data from web requests in HTTP request driven applications. SQLITE has been the database of choice on mobile platforms because of his light footprint. In this Blog we explore the basics for integrating SQLLITE with iPhone Native application. Fortunately, MacOS X is shipped with SQLite pre-installed, including an interactive environment for issuing.SQL commands from within a Terminal window. Using SQLite3 database in iphone app, for that we will need to add libsqlite framework in application. Right click on frameworks->Add Existing.

In the search bar type “libsql” and it will show you some 4 frameworks with same name.You have to choose libsqllite, the current version as of this document is 3 so i assume libsqlite3.dylib for the purpose of this blog.

Add SQLite to XCode Project

click on add button to add the framework to project. To create a database you can use terminal or you can use firefox extension for sqlite3 i.e sqlite manager 0.7.7. Creating database using terminal: open terminal and set the path where you want to save database. 1. sqlite3 data.sqlite3 instead of “data” you can use any other name. 2. Create the required tables in SQLite
After creating tables, typing in .tables will give you tables in data.sqlite3 database.

Command to see tables in SQLite database

3. Lets do a few sample inserts in the SQLite DB:
INSERT INTO users (user , description) VALUES( 'User1', 'Description 1');
INSERT INTO users (user, description ) VALUES( 'User 2', 'Description 2');
4. Lets retrieve the list of records saved in the SQLite DB.
select * from users;

List Records SQLite

Creating database using sqlite manager: SQLiteManager is a firefox extension that eases the operations with SQLite. Open firefox and download and install sqlite manager 0.7.7. Restart firefox after installing, go to tools and you will see the option for SQLiteManager. Clicking the SQLite option will open a tab which will let you create a new database:

Creating SQLite DB with SQLiteManager

Once database is created, you can create new tables in the database.

clicking on the add button will invoke a popup as shown in the screenshot below.

Create table in SQLite iOS

enter the values and click ok. After records been added it looks like above screenshot. Now we will import the database into our project. Right click on Resources->Add->Existing File and select data sqlite3. This will add data.sqlite3 file into Resources folder. The Coding begins Open up the “User.h” file from the “Classes” folder and edit its contents
#import <UIKit/UIKit.h>

@interface User : NSObject {
	NSString *name; // member variable
	NSString *description;// member variable
	NSString *imageURL; // member variable

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSString *imageURL;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u;

Lets decode this code a bit. initWithName line, this line will allow you to create a new object with the required data, we could have used the default init function, but it will be easier for us to define our own. Now we will actually have to implement the User Object, open up the “User.m” file and edit its contents
#import "User.h"

@implementation User
@synthesize name, description, imageURL;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u { = n;
	self.description = d;
	self.imageURL = u;
	return self;
The above code basically stores the supplied data from the initWithName function and return the object (self). Open up the “SQLite3TutorialAppDelegate.h”

#import <UIKit/UIKit.h>
#import  // (if this shows error "no such directory" then you can use #import "/usr/include/sqlite3.h"

// Import the SQLite database framework
@interface SQLiteTutorialAppDelegate : NSObject {
UIWindow *window;
UINavigationController *navigationController;

// Database variables
NSString *databaseName;
NSString *databasePath;

// Array to store the user objects
NSMutableArray *users;

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@property (nonatomic, retain) NSMutableArray *users;

// Now open up the “SQLiteTutorialAppDelegate.m”
- (void)applicationDidFinishLaunching:(UIApplication *)application {

// Setup some globals
databaseName = @"data.sqlite3";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

// Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];

// Query the database for all user records and construct the "users" array
[self readUsersFromDatabase];
// Configure and show the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];

-(void) checkAndCreateDatabase{

// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;

// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything

if(success) return;
// If not then proceed to copy the database from the application to the users filesystem

// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];

-(void) readUsersFromDatabase {
// Setup the database object
	sqlite3 *database;
	// Init the User Array
	users = [[NSMutableArray alloc] init];

	// Open the database from the users filessystem
	if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
		// Setup the SQL Statement and compile it for faster access
		const char *sqlStatement = "select * from users";
		sqlite3_stmt *compiledStatement;
		if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
			// Loop through the results and add them to the feeds array
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				// Read the data from the result row
				NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
				NSString *aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
				NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

				// Create a new user object with the data from the database
				User *user = [[user alloc] initWithName:aName description:aDescription url:aImageUrl];

				// Add the user object to the users Array
				[users addObject:user];

				[user release];
		// Release the compiled statement from memory
sqlite3_column_text is used if record is varchar You can use sqlite3_column_int for integer type. For more you can read sqlite3_close.The sqlite3_close() routine is the destructor for the sqlite3 object. Calls to sqlite3_close() return SQLITE_OK if the sqlite3object is successfully destroyed and all associated resources are deallocated. readUsersFromDatabase will fetch all records from users table. Thats it for this tutorial, Enjoy integrating your iPhone apps with SQLite.

Top iPhone Game Engines

There are several great game frameworks available for download. Some of these frameworks require little to no programming experience and, best of all, some of them are free. In this blog you will find a list of the best to date iPhone and mobile game development frameworks.

What is Game Engine? A game engine is a system designed for the creation and development of video games. There are many game engines that are designed to work on video game consoles and personal computers. The core functionality typically provided by a game engine includes a rendering engine (“renderer”) for 2D or 3D graphics, a physics engine or collision detection (and collision response), sound, scripting, animation, artificial intelligence, networking, streaming, memory management, threading, localization support, and a scene graph.

COCOS 2D (Pricing Below) Skill Level: Intermediate/Advanced (basic programming knowledge and basic understanding of the C-programming language) Cocos2d for iPhone is a framework for creating 2d games, demos, and interactive interfaces. Cocos2d is an open source Objective-C library. Using Cocos2D, you will need a basic understanding of the C-language. The libraries and API’s for Cocos2d allow developers to easily use scene management, sprites, effects, particles, menus, and much more. Ported to Linux, Mac OS X, iOS, and windows. iOs port is written in Objective-C and integrated with Box2D and Chipmunk physics engines.

  • Integrated physics engine (both Box2d and Chipmunk)
  • OpenGL ES 1.1 based (iOS) / OpenGL 1.5 based (Mac)

CORONA MOBILE DEVELOPMENT PLATFORM (Pricing Below) Skill Level: Intermediate (Basic knowledge of programming techniques) Corona makes it easy for any user with little programming knowledge to create full featured mobile applications. Corona abstracts Objective-C from mobile development and brings to life the ease of the LUA programming language. Using Corona and LUA, you can easily create a ‘Hello World’ application in one line of code, or easily implement physics in only 5 lines. Creating mobile games has never been easier. Corona has a fantastic built-in mobile simulator, so you can test and build everything out without having to use Xcode.


  • Proprietary OpenGL-ES rendering engine allows for full hardware acceleration of graphics, including sprites that animate at full GPU speed.
  • Transition library enables tweening of Corona-powered sprites’ position, rotation, alpha, or any other property.
  • Supports native iPhone and Android UI. Developers can access the iPhone’s native text features including all fonts, multi-line fields, and keyboard input.
  • Apps built with Corona start at under 400KB in size.
  • Subscription-based purchase model allows users to have new updates as soon as they are rolled out.
  • Full feature integration with device camera, accelerometer, magnetometer, video player, compass, and/or GPS.

GAME SALAD (Pricing Below) Skill Level: Beginner Game Salad is an excellent tool/framework for creating iPhone games. It’s not only for beginners, even if you are an advanced game developer you will still be able to take advantage of some of the awesome features that Game Salad has to offer. Game Salad has a WYSIWYG creator where you can literally drag and drop images and objects onto the creator. Then you can assign specific attributes to these objects and images such as collision detection, gravity, animation, and much more. You don’t need to have any programming experience to develop your iPhone game masterpiece.


  • Used by game developers for rapidly prototyping, building and self-publishing cross-platform games and interactive media.
  • The application runs on Mac OS X and can produce iPhone, web browser-based content in HTML 5, and Mac applications.

iTorque 2D (Pricing Below) Skill Level: Beginner/Intermediate (A little knowledge of C++ would be helpful) Torque Game Builder is one of the worlds easiest to use 2d game creator. Garage Games has now created a branch of the Torque 2D game builder which is called iTorque2D. iTorque2D has a WYSIWYG interface which allows users to drag and drop elements onto the interface and add functionality to each object through a simple to use interface. There may be some portions of this engine that may require a user to manipulate a little C++ code; however, the engine is very intuitive to new game creators.


  • TGE provided networking code, scripting, in-engine world editing, and GUI creation.
  • The source code could be compiled for Windows, Macintosh, Linux, Wii, Xbox 360, and iPhone platforms.

Sparrow Framework (Pricing Below) Skill Level: Intermediate/Advanced (You will need knowledge of basic C-programming techniques) Sparrow Framework is an open-source project which eliminates the need for any OpenGL code. Sparrow Framework allows developers to write clean C-code which blends seamlessly with Cocoa. Additionally, Sparrow allows users to leverage their Flash and Flex skills with no need to learn a new API. If you consider yourself a good C-programmer and would like to leverage features that cut your development time in half, you may want to check out the Sparrow Framework.


  • No need to write any OpenGL code and easy to extend, even with custom OpenGL code
  • Allows direct use of iPhone features like accelerometer or vibration – no need for a wrapper!
  • Leverages your existing Flash/Flex skills (no need to learn a new API!)

Unity 3D Game Development Tool (Pricing Below) Skill Level: Advanced (You will need basic programming knowledge as well as 3d knowledge) Unity 3D has the all-in-one programming and graphic creation tools for mobile, console, and desktop game publishing. If you are familiar with 3D rendering tools and have a basic knowledge of programming and scripting, you are well on your way to create your first 3D mobile game. The easy-to-use tools by Unity 3D integrates easily and seamlessly with each other. Unity is offered as two different types of licenses. Unity and Unity Pro. If you are a company that turned over more than $100,000 for the previous fiscal year you must purchase Unity Pro. Otherwise, as a small indie developer you can have the license for free.

  • Integrated development environment with hierarchical, visual editing, detailed property inspectors and live game preview.
  • Deployment on multiple platforms like Microsoft Windows, Mac OS X , Nintendo, iPhone/iPad , Android
  • Assets are automatically imported, and are re-imported if the asset is updated. Unity supports integration with 3ds Max, Maya, Softimage, Blender, Modo, ZBrush, Cinema 4D, Cheetah3D, Photoshop and Allegorithmic Substance.
  • Graphics engine uses Direct3D (Windows), OpenGL (Mac, Windows), OpenGL ES (iOS, Android), and proprietary APIs (Wii).
  • Support for bump mapping, reflection mapping, parallax mapping, Screen Space Ambient Occlusion, dynamic shadows using shadow maps, render-to-texture and full-screen post processing effects.
Frameworks Price Platform supported
Cocos2d Free ios, Android
Corona OS developer: $199/yrAndroid developer: $199/yrAll Platforms: $349/yr ios, Android, Amazon Kindle Fire
Game Salad Free ios, Android
iTorque2d $128 Mac Os X, Microsoft Windows
Sparrow Free ios
Unity 3D Unity: FreeUnity Pro: $1500

Microsoft Windows, Mac OS X, Nintendo, ios, Android

Developing First IPhone Application

In this tutorial you will get a brief introduction on how to get started with your first iPhone application. To begin you will need the latest version of the iPhone SDK. With the SDK you get some tools like Xcode, Interface Builder, iPhone simulator etc.

Purpose of the “Hello Friend” app Using the app a user will be able to enter his/her full name and click a button to see a message appear. The message will say “Hello Friend, my name is ……!” This app will not only introduce you to some of its tools but will also show you how to use controls, respond to events and create new views.

Creating a new project Launch Xcode and click on File -> New Project -> Select Application (under iPhone OS) -> select Window-> Based Application project template and click on choose. In the next screen you will be asked to save your project and give it a name. Xcode creates some files for us based on the name of the project, so you need to be careful with the name you provide. Here the name given to the project is “HelloFriend”. All the class files are stored under the “Classes” folder, some special files are listed under “Other Sources”, all the view files and resources show up under “Resources”, and any library or frameworks we add to our project are listed under the “Frameworks” folder. It is important that we save all the images, files, databases, and views in the “Resources” folder because all the iPhone apps run in its own sand box; which means it can only access files placed under the resources folder.

Interface Builder Using Interface Builder we can design our application by adding controls or creating additional views. The files that the Interface Builder creates get saved with a .xib extension and are called nib files. Every project gets one nib file which is called “MainWindow.xib” which can be found under “Resources”. An iPhone application has only one window (MainWindow.xib) unlike a desktop application which is created with multiple windows; however, we can create multiple views which are added to the window. Double click on “MainWindow.xib” to launch the Interface Builder. Every nib file has at least two files; File’s Owner and First Responder which cannot be deleted. Every other objects apart from the first two, represents an instance of an object which gets created when the nib file loads. File’s Owner simply shows that it owns the object in the nib file. First Responder tells us which object are we currently interacting with; like the textbox, buttons. The third object which is special to the MainWindow.xib file is called “Hello Friend App Delegate” and this file represents “HelloFriendAppDelegate” class. Last but not the least the view represents the object which we design in our apps.

Creating a new view If we had created this project using “View-Based Application” project template then there would have been no need of creating another view from scratch, but where is the fun in that. In Interface Builder create a new view by clicking File -> New -> Select Cocoa Touch -> View and click on choose. Let’s save the view in the project folder by naming it “HelloFriend” and once we are done with that IB (Interface Builder) will prompt us to add the view to the current project; click on “Add” and it will show up in Xcode. In Xcode move your view to the Resources folder.

Creating a view controller We have a view; now let’s create a view controller to manage the view. In Xcode create a new view controller by selecting classes and clicking File -> New File -> Select Cocoa Touch Classes under iPhone OS -> select UIViewController -> click on choose and name your file “HelloFriendController” without changing the extension. The newly created class inherits from UIViewController which knows how to interact with a view. Now that we have our view and the controller class, there must be some way to connect these two files and we can do it by setting the class property of the File’s Owner. Double click “HelloFriend.xib” file in Xcode to launch Interface Builder and select File’s Owner->select Tools->Identity Inspector and under “Class Identity” category, change the class to “HelloFriendController”. Once we are done with this, we need a way to control the view in the nib file from code and this could be done by connecting the view instance variable to the view object in the nib. The connection is made using “outlets”. Select Tools -> Connections Inspector create a connection from the view variable to the view in the nib file. Move your mouse over the empty circle to see it change to a plus symbol indicating that a connection can be created. Click on circle and drag your mouse to the view in the nib file and release. As you do this you will see a blue line being created from the circle to the mouse.

Adding controls to the view We require two text boxes, one label, and a button (Round Rect Button). From the library drag and drop the controls to the view and align it. After you have added the controls let’s change some of its properties, starting with the text boxes. Select the first text box and open Attributes Inspector by selecting Tools -> Attributes Inspector. Under Placeholder enter “First name”, under “Text Input Traits” change Capitalize property to “Words” and change the Return key property to “Done”. Apply the same settings for the other text box but change the Placeholder to say “Last name”. Select the label and delete its text property, since we do not want the label to say anything until the button is clicked. Double-click the button to edit the title of the button and type in “Click Me”. Save and quit Interface Builder as we have successfully designed our view.

Connecting instance variables to the objects in the view We still need some way to interact with the controls on the view, in code and this is where outlets will help us out. IBOutlet is a special keyword if used with an instance variable, will make the variable appear in Interface Builder. Since IBOutlet makes the variable appear in Interface Builder, using IBAction as a return type for a method will have the opposite effect. Using IBAction we can handle an event triggered by any control placed on the view. Let’s see how this works; open HelloFriendController.h file in Xcode and type  the following code

@interface HelloFriendController: UIViewController {
IBOutlet UITextField *txtFirstName;
IBOutlet UITextField *txtLastName;
IBOutlet UILabel *lblMessage;
- (IBAction) btnClickMe_Clicked:(id)sender;
- (void)dealloc {
[txtFirstName release];
[txtLastName release];
[lblMessage release];
[super dealloc];

All the variables above are marked with IBOutlet and Interface Builder will make these available to itself, so proper connections can be made. We also have a method whose return type is IBAction (void); Interface Builder will also make this method available to itself so we can choose which event will call this method. The method also takes a parameter called “sender” which is the object which triggered the event. The variables are released in the dealloc method as shown above. Let’s connect these instance variables to the controls on the view (HelloFriend) as described earlier. Open Interface Builder by double-clicking HelloFriend.xib file and select File’s Owner, open Connections Inspector to see all the variables present under Outlets and to create connections. Let’s hook up the button click event to the “btnClickMe_Clicked” method. Select the button and under the Events list it seems that we do not have a button click event; however, we do have a “Touch up Inside” event which is raised when the button is touched and released symbolizing a click. With the button selected click the circle next to “Touch Up Inside” and drag your mouse over to File’s Owner and release to have the method name show; simply click on the method name to create a connection.

Handling events Let’s write some code in btnClickMe_Clicked event to read the first and last name and display a message in the label. This is how the code looks like

- (IBAction) btnClickMe_Clicked:(id)sender {
NSString *FirstName = txtFirstName.text;
NSString *LastName = txtLastName.text;
NSString *Message = nil;
if([FirstName length] == 0 && [LastName length] == 0)
Message = [[NSString alloc] initWithFormat:@"Hello Friend!!!"];
else if ([FirstName length] > 0 && [LastName length] ==0)
Message = [[NSString alloc] initWithFormat:@"Hello Friend, my name is %@!", FirstName];
else if ([FirstName length] == 0 && [LastName length] == 0)
Message = [[NSString alloc] initWithFormat:@"Hello Friend, my name is %@!", LastName];
Message = [[NSString alloc] initWithFormat:@"Hello Friend, my name is %@ %@!", FirstName, LastName];
lblMessage.text = Message;
//Release the object
[Message release];

The method does few simple things; it finds out the first and last names and figures out what message to display in the label. We also create a temporary variable called “Message” to hold the message which will be displayed in the label. The variable is allocated and initialized by alloc and initWithFormat messages respectively. The variable is released in the end because when working with the iPhone we are responsible of cleaning up the memory. The easiest way to remember when to release objects is; if you create it then you own the object and hence you are responsible of releasing it. If you click on Build and Go, the view will not be visible because we have not yet added it to the window. Let’s see how we can do that.

Adding view to the window Now we cannot drag the view and add it to the window, so we need another way to add the view as a sub view to the window. We already know that “HelloFriendController” is the view controller of the view “HelloFriend” and “HelloFriendAppDelegate” is the application delegate where the window is made visible in applicationDidFinishLaunching method. It is in that method we will add the view as a sub view to the window. Before we do that, the application delegate (HelloFriendAppDelegate) needs to know about our view controller. Add the following lines to HelloFriendAppDelegate.h file to change the file like this

@class HelloFriendController;
@interface HelloFriendAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
HelloFriendController *hvController;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) HelloFriendController *hvController;

From the above code we first add a forward class declaration of “HelloFriendController” because we do not want any circular dependency when we import the header file of “HelloFriendController” in HelloFriendAppDelegate.m. A variable and a property of type HelloFriendController is also declared. The property as you can see is declared with a couple of attributes called “retain” and “nonatomic”. The retain attribute will increase the reference count of the instance variable by one and nonatomic is used because our program is not multi-threaded. A lot of first time users miss to synthesize the property we declared, so let’s do that now at the top of the HelloFriendAppDelegate.m file and the code looks like this

@implementation HelloFriendAppDelegate
@synthesize window, hvController;

The view is added as a sub view to the window in applicationDidFinishLaunching method and this is how the code looks like

- (void)applicationDidFinishLaunching:(UIApplication *)application {
HelloFriendController *hvc = [[HelloFriendController alloc]
initWithNibName:@"HelloFriend" bundle:[NSBundle mainBundle]];
self.hvController = hvc;
[hvc release];
[window addSubview:[self.hvController view]];
// Override point for customization after application launch
[window makeKeyAndVisible];

The second line shows that we imported the header file of “HelloFriendController” and we also synthesized the property hvController. In the “earlier” days in order to create a property we had to create getter and setter methods which would be something like getHVController and setHVController. The synthesize keyword automatically generates these methods for us. In applicationDidFinishLaunching method we allocate and initialize a temporary variable, assign it to our property, release it, and the view associated with the view controller is added as a sub view to the window. The key thing to remember here is that the view message is passed to the “hvController” which returns the view and is added as sub view to the window. A valid view is returned because we created a connection from the view instance variable to the view in the nib file. The property is finally released in the dealloc method as shown below

- (void)dealloc {
[hvController release];
[window release];
[super dealloc];

We have always allocated and initialized variables in one single line as seen below, this is usually the accepted way but the same code can be written in a different way as seen below:

HelloFriendController *hvc = [HelloFriendController alloc];
hvc = [hvc initWithNibName:@"HelloFriend" bundle:[NSBundle mainBundle]];
Build and go to test your application.

Hiding the keyboard Wait a minute; clicking the “Done” button doesn’t do anything. Ideally we would like to hide the keyboard when the “Done” button is clicked no matter which text box we are currently editing. To hide the keyboard we need to do two things; set the delegate of the keyboard to File’s Owner and implement a method called textFieldShouldReturn in HelloFriendController.m file. To set the delegate, open Interface Builder by double clicking HelloFriend.xib, select the first text box and click on Tools -> Connections Inspector. Click and drag your mouse by selecting the empty circle next to delegate under “Outlets” and release your mouse over to File’s Owner. Assign the delegate for the next text box in the same manner. The method textFieldShouldReturn gets called when the “Done” button is clicked and this is how the code looks like

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;

The method gets a parameter called sender, which is the object that triggered the event. We will use the same object to which we send the resignResponder message, which will hide the keyboard on the textbox. The boolean “Yes” is returned to tell the sender that the first responder is resigned.

Conclusion We hope that you had fun with this tutorial and feel a little confident in writing your next great iPhone app. Please leave your comments and share your thought with us. Happy Programming!

PS: We have re-written this tutorial hoping that it would be easier to follow. If you have any questions please do not hesitate to send your revert here and we will be happy to help you out.

Class Declaration: C++ vs. Objective-C

It is hard to show with a single example all the differences between Objective-C and C++ for class declaration and implementation. In the following, the differences are exposed sequentially and specifically.

Basic Difference

Objective-C is an object-oriented language: it manages classes and objects. Objective-C uses a strict object model, unlike C++ which has many discrepancies against the ideal object model. For instance, in Objective-C, classes are objects and can be dynamically managed: it is possible to add classes at run-time, create instances based on the name of the class, ask a class for its methods, and so on. This is much more powerful than C++ RTTI.

Root class, type id, nil and Nil values

In an object-oriented language, each program makes use of a set of classes. Unlike C++, Objective-C defines a root class. Every new class should be a descendant of the root class. In Cocoa, that class is NSObject, and it provides a huge number of facilities for the run-time system.

Strictly speaking, every object should be of type NSObject, and every pointer to an object could be declared as NSObject*. In fact, one can use the type id instead. This is a short and handy way to declare a pointer to any object, and provides dynamic type-checking instead of static type-checking. It is very useful for some weak typing on generic methods. Please note that a null pointer to an object should be set to nil, not NULL. These values are not interchangeable. A normal C pointer can be set to NULL, but nil was introduced in Objective-C for pointers to objects. In Objective-C, classes are also objects (meta-class instances), and it is possible to declare a pointer to a class. Their null value is Nil.

Attributes and methods

class Test { double x; public: int f(int x); float g(int x, int y); };  int Test::f(int x) {...} float Test::g(int x, int y) {...}
@interface Test : NSObject { double x; } -(int) f:(int)x; -(float) g:(int)x:(int)y; @end  @implementation Test -(int) f:(int)x {...} -(float) g:(int)x:(int)y {...} @end

In C++, attributes and methods are declared together inside the braces of the class. Method implementation syntax is similar to C, with the addition of the scope resolution operator (Test:: ).

In Objective-C, attributes and methods cannot be mixed. The attributes are declared in braces, the methods follow. Their implementation lies in an @implementation block. This is a major difference with C++, since some methods can be implemented without being exposed in the interface. Briefly, this is a way to clean up header files by removing unnecessary declarations

Instance methods are prefixed by the minus symbol “-”, and class methods by the plus symbol

“+”; this symbol has nothing to do with the UML notation and the meaning public or private. The type of the parameters is enclosed in parenthesis, and the parameters are separated by the symbol “:”.

In Objective-C, there is no need for a semi-colon at the end of a class declaration. Also note that the keyword to declare a class is @interface and not @class. The keyword @class is only used in forward declarations. Finally, if there is no instance data in a class, the braces, which would enclose nothing, can be omitted. Forward declarations: @class, @protocol

To avoid cyclic dependencies in header files, in C++ uses keyword class is used; in Objective-C, it is @class. The keyword @protocol can also be used to anticipate the declaration of a protocol.

//In file Test.h #ifndef __TEST_H__ #define __TEST_H__ class Bar; //forward declaration class Test { Bar* bar; public: void useBar(void); }; #endif
//In file Test.cpp #include "Test.h" #include "Bar.h" void Test::useBar(void) { ... }
//In file Test.h @class Bar; //forward declaration @interface Test : NSObject { Bar* bar; } -(void) useBar; @end
//In file Test.m #import "Test.h" #import "Bar.h" @implementation Test -(void) useBar { ... } @end

public, private, protected

One major feature of the object model is data encapsulation, which limits the visibility of data to some parts of the code, in order to ensure its integrity.

class Test { public: int x; int apple(); protected: int y; int pear(); private: int z; int banana(); };
@interface Test : NSObject { @public int x; @protected: int y; @private: int z; } -(int) apple; -(int) pear; -(int) banana; @end

In C++, attributes and methods can belong to a public, protected or private scope. The default mode is private.

In Objective-C, only the instance data can be public, protected or private, and the default visibility is protected. Methods can only be public. However, it is possible to mimic the private mode, by implementing some methods in the @implementation, without declaring them in the @interface, or using the notion of class category. It does not prevent methods from being called, but they are less exposed. Implementing a method without a previous declaration is a special property of Objective-C.

Inheritance cannot be tagged public, protected or private. The only way is public.

static attributes

It’s not possible in Objective-C to declare a class data attribute (static as in C++). However, it is possible to do the same thing in a different way: use a global variable in the implementation file (optionally with the static C keyword to limit the scope). The class can then use accessors on it (with class methods or normal methods), and its initialization can be done in the initialize method of the class.