Archive for the ‘Objective-C’ 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

Introduction

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
  4.  
  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.    self.name = 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 = rawStudents.data(using: .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.  }
  7.  
  8.  class BlogPost<T> {
  9.    enum BlogPostType {
  10.      case tutorial
  11.      case article
  12.    }
  13.    
  14.    let title: T
  15.    let type: BlogPostType
  16.    let category: TeamType
  17.    let publishDate: Date
  18.    
  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.  }
  26.  
  27.  let type: TeamType
  28.  let author: T
  29.  let teamLead: T
  30.  let blogPost: BlogPost<T>
  31.  
  32.  init(type: TeamType, author: T, teamLead: T, blogPost: BlogPost<T>) {
  33.    self.type = type
  34.    self.author = 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
  3.  
  4.  class BlogPost {
  5.    // original code
  6.  }  
  7.  
  8.  // original code
  9.  let blogPost: BlogPost
  10.  
  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!  

Bundle and plist in Objective C – An Overview

Bundle: A bundle is a structure used for packaging software on Mac OS X. The main bundle is simply the bundle of the application that is running. So, for instance, the main bundle of the Apple mail program is /Applications/Mail.app. Types of Bundle: There are three general types of bundles: Application bundles Application bundles contain an executable and all its related resources, such as nib files, image files, and localized strings. Plug-in bundles Plug-in bundles provide code that extends or enhances the functionality of a host application in some way. Framework bundles Framework bundles contain dynamic shared libraries, as well as header files, images, and documentation. How to access bundle resource: When a user launches an application, it finds the code and resources in the main bundle that it immediately needs and loads them into memory. Thereafter, the application can dynamically (and lazily) load code and resources from the main bundle or subordinate bundles as required. plist: This file is an XML-based text file that contains specific types of key-value pairs. These key-value pairs specify information about the bundle, such as its ID string, version number, development region, type, and other important properties. Importance: A great way to store dictionary data that does not change during runtime is in a .plist file. Example:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Info.plist"];
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:finalPath];
Notes
  • The settings bundle is for having settings that show up in the system Settings.app.
  • You can use a plist to store settings that you change within the app itself.
Enjoy your day !!

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
CREATE TABLE users id INTEGER PRIMARY KEY AUTOINCREMENT, user VARCHAR(255) DEFAULT NULL;
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;

@end
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 {
	self.name = n;
	self.description = d;
	self.imageURL = u;
	return self;
}
@end
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;
@end

// 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_finalize(compiledStatement);
	}
	sqlite3_close(database);
}
sqlite3_column_text is used if record is varchar You can use sqlite3_column_int for integer type. For more you can read http://www.sqlite.org/keyword_index.html 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.

Features:
  • 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.

Features:

  • 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.

Features:

  • 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.

Features:

  • 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.

Features:

  • 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.

Features:
  • 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


Starting with Objective C

Basics of Objective C Objective-C is a reflective, object-oriented programming language that adds Small talk-style messaging to the C programming language. Objective-C is a strict superset of C; it is possible to compile any C program with an Objective-C compiler, and to freely include C code within an Objective-C class. Creating classes Objective-C requires that the interface and implementation of a class be in separately declared code blocks. By convention, we place the interface in a header file and the implementation in a code file. The header files, normally suffixed .h, are similar to C header files while the implementation (method) files, normally suffixed .m, can be very similar to C code files. Interfaces The interface of a class is usually defined in a header file. A common convention is to name the header file after the name of the class, e.g. Fraction.h would contain the interface for the class Fraction. Fraction.h @interface Fraction: NSObject { int numerator; int denominator; } //multiple parameters first parameter is n and second parameter is d and Deno is named argument. -(void) setNumerator:(int) n Deno:(int) d; -(void) print;                         // no parameter -(void) setNumerator:(int) d;             // single parameter d is only parameter @end
      • Inheritance is specified as Class: Parent, as seen with Fraction: NSObject.
      • Instance variables go between @interface Class: Parent { …. }
      • Instance methods follow after the member variables. The format is:
      • scope (returnType) method Name: (parameter1Type) parameter1Name; scope  refers to  class or instance. instance methods begin with – , class level methods begin with +
      • Interface ends with @end.
Implementation The actual code is written in the implementation file. “@implementation ClassName” starts the implementation “@end” ends it. Fraction.m @implementation Fraction -(return type)methodname: (parameter1type)  parameter1name{ …….// code to be written } @end  Once the class is written, it can be instantiated. Example shows how to do this: Fraction *frac = [[Fraction alloc] init];  //instantiation In this Fraction is a class. Memory is allocated by alloc and then initialized by init.  Access privileges  The default access is @protected. But it has public/private/protected access.  Public variable can be accessed outside the class but private variable can be accessed within the the class only. Following example shows access: Access.h  #import <Foundation/NSObject.h> @interface Access: NSObject { @public int publicVar; @private int privateVar; } @end  Inheritance  If we have already some class we can inherit it in other class. <import number.h> @interface fraction: number  //class fraction inherits class number { } Now by inheriting the class we can use the methods of class number in class fraction. Also we can access Protocols Objective-C was extended at NeXT to introduce the concept of multiple inheritance of specification, but not implementation, through the introduction of protocols. Locking.h @protocol locking -(void) lock; -(void) unlock; @end @interface SomeClass : SomeSuperClass <Locking> @end Constructors Constructor is defined as method having same name as class. In objective c we can define constructor as follow: Fraction.h -(Fraction*) Numerator: (int) n Fraction.m (Fraction*) Numerator: (int) n { self = [super init]; if ( self ) { //code to be written } } Accessing it’s super constructor is done through [super init] and this is required for proper inheritance. If ( self ) is the same as if ( self != nil ) to make sure that the super constructor successfully returned a new object. nil is Objective-C’s form of NULL from C/C++. The default constructor is -(id) init.  Memory management: Retain and Release #import “Fraction.h” #import <stdio.h> int main( int argc, const char *argv[] ) { Fraction *frac1 = [[Fraction alloc] init]; Fraction *frac2 = [[Fraction alloc] init]; // print current counts printf( “Fraction 1 retain count: %i\n”, [frac1 retainCount] ); printf( “Fraction 2 retain count: %i\n”, [frac2 retainCount] ); // increment them [frac1 retain]; // 2 [frac2 retain]; // 2 // print current counts printf( “Fraction 1 retain count: %i\n”, [frac1 retainCount] ); printf( “Fraction 2 retain count: %i\n”, [frac2 retainCount] ); // decrement [frac1 release]; // 2 [frac2 release]; // 1 // print current counts printf( “Fraction 1 retain count: %i\n”, [frac1 retainCount] ); printf( “Fraction 2 retain count: %i\n”, [frac2 retainCount] );

// release them until they dealloc themselves [frac1 release]; // 0 [frac2 release]; // 0 [super dealloc] } Initially, count is 1 The retain calls increment the counter.The release calls decrement it.One can get the count as an int by calling [obj retain Count].Once the retain Count reaches 0, both objects dealloc themselves.

Dealloc When your object contains other objects, you must free them whenever you yourself dealloc. One of the nice advantages to Objective-C is you can pass messages to nil, so there isn’t a lot of error checking to release an object. In above example we have written [super dealloc] in the end.

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

C++
Objective-C
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.

C++
//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) { ... }
Objective-C
//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.

C++
Objective-C
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.