Search Posts in my Blog

Thursday 20 April 2017

iOS Interview Questions for Experienced Developers - 2017 - PART 1

1.Whats fast enumeration?
Fast enumeration is a language feature that allows you to enumerate over the contents of a collection. (Your code will also run faster because the internal implementation reduces message send overhead and increases pipelining potential.) 

2. Whats a struct?
A struct is a special C data type that encapsulates other pieces of data into a single cohesive unit. Like an object, but built into C. 
3. Explain retain counts.
Retain counts are the way in which memory is managed in Objective-C. When you create an object, it has a retain count of 1. When you send an object a retain message, its retain count is incremented by 1. When you send an object a release message, its retain count is decremented by 1. When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. If an objectʼs retain count is reduced to 0, it is deallocated.

4. Whats the difference between frame and bounds?
The frame of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within. The bounds of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0). 
5. Is a delegate retained? 
No, the delegate is never retained! Ever! 
6. Outline the class hierarchy for a UIButton until NSObject. 
UIButton inherits from UIControl, UIControl inherits from UIView, UIView inherits from UIResponder, UIResponder inherits from the root class NSObject 
7. What is dynamic? 
You use the @dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution. It suppresses the warnings that the compiler would otherwise generate if it can’t find suitable implementations. You should use it only if you know that the methods will be available at runtime 
8. If I call performSelector:withObject:afterDelay: – is the object retained? 
Yes, the object is retained. It creates a timer that calls a selector on the current threads run loop. It may not be 100% precise time-wise as it attempts to dequeue the message from the run loop and perform the selector. 
9.Can you explain what happens when you call autorelease on an object?

When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. The object is added to an autorelease pool on the current thread. The main thread loop creates an autorelease pool at the beginning of the function, and release it at the end. This establishes a pool for the lifetime of the task. However, this also means that any autoreleased objects created during the lifetime of the task are not disposed of until the task completes. This may lead to the taskʼs memory footprint increasing unnecessarily. You can also consider creating pools with a narrower scope or use NSOperationQueue with itʼs own autorelease pool. (Also important – You only release or autorelease objects you own.)

10.Whats the NSCoder class used for?
NSCoder is an abstractClass which represents a stream of data. They are used in Archiving and Unarchiving objects. NSCoder objects are usually used in a method that is being implemented so that the class conforms to the protocol. (which has something like encodeObject and decodeObject methods in them).

11. Whats an NSOperationQueue and how/would you use it?
The NSOperationQueue class regulates the execution of a set of NSOperation objects. An operation queue is generally used to perform some asynchronous operations on a background thread so as not to block the main thread. 

12.Explain the correct way to manage Outlets memory.
Create them as properties in the header that are retained. In the viewDidUnload set the outlets to nil(i.e self.outlet = nil). Finally in dealloc make sure to release the outlet. 
13.Is the delegate for a CAAnimation retained?
Yes it is!! This is one of the rare exceptions to memory management rules.

14.What happens when the following code executes? Ball *ball = [[[[Ball alloc] init] autorelease] autorelease]; 
It will crash because itʼs added twice to the autorelease pool and when it it dequeued the autorelease pool calls release more than once.

15. Explain the difference between NSOperationQueue concurrent and non-concurrent.

In the context of an NSOperation object, which runs in an NSOperationQueue, the terms concurrent and non-concurrent do not necessarily refer to the side-by-side execution of threads. Instead, a non-concurrent operation is one that executes using the environment that is provided for it while a concurrent operation is responsible for setting up its own execution environment. 


16. Implement your own synthesized methods for the property NSString *title. 
Well you would want to implement the getter and setter for the title object. Something like this: view source print?
page2image26320
- (NSString*) title // Getter method { return title; }
- (void) setTitle: (NSString*) newTitle //Setter method { if (newTitle != title) {
[title release]; title = [newTitle retain]; // Or copy, depending on your needs. } } 
17.Implement the following methods: retain, release, autorelease. 
-(id)retain { NSIncrementExtraRefCount(self); return self; } -(void)release {
if(NSDecrementExtraRefCountWasZero(self)) {
NSDeallocateObject(self); }
} -(id)autorelease { // Add the object to the autorelease pool [NSAutoreleasePool addObject:self]; return self 
18. What are the App states. Explain them? 
Not running State: 
The app has not been launched or was running but was terminated by the system. 
Inactive state: 
The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state. The only time it stays inactive for any period of time is when the user locks the screen or the system prompts the user to respond to some event, such as an incoming phone call or SMS message.
Active state: 
The app is running in the foreground and is receiving events. This is the normal mode for foreground apps. 
Background state:
The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state. For information about how to execute code while in the background, see “Background Execution and Multitasking.” 
Suspended state: 
The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app. 
19. What is Automatic Reference Counting (ARC) ? 
ARC is a compiler-level feature that simplifies the process of managing the lifetimes of Objective-C objects. Instead of you having to remember when to retain or release an object, ARC evaluates the lifetime requirements of your objects and automatically inserts the appropriate method calls at compile time. 
20.Multitasking support is available from which version? 
iOS 4 and above supports multi-tasking and allows apps to remain in the background until they are launched again or until they are terminated. 
21.How many bytes we can send to apple push notification server. 
256bytes. 
22.What is the difference between retain & assign? 
Assign creates a reference from one object to another without increasing the source’s retain count. if (_variable != object) { [_variable release]; _variable = nil; _variable = object; } Retain creates a reference from one object to another and increases the retain count of the source object. if (_variable != object)
{ [_variable release]; _variable = nil; _variable = [object retain]; }

23.Why do we need to use @Synthesize?
We can use generated code like nonatomic, atmoic, retain without writing any lines of code. We also have getter and setter methods. To use this, you have 2 other ways: @synthesize or @dynamic: @synthesize, compiler will generate the getter and setter automatically for you, @dynamic: you have to write them yourself.@property is really good for memory management, for example: retain.How can you do retain without @property?
if (_variable != object) { [_variable release]; _variable = nil; _variable = [object retain]; }
How can you use it with @property?self.variable = object;When we are calling the above line, we actually call the setter like [self setVariable:object] and then the generated setter will do its job 

24.What is categories in iOS?
A Category is a feature of the Objective-C language that enables you to add methods (interface and implementation) to a class without having to make a subclass. There is no runtime difference—within the scope of your program—between the original methods of the class and the methods added by the category. The methods in the category become part of the class type and are inherited by all the class’s subclasses.As with delegation, categories are not a strict adaptation of the Decorator pattern, fulfilling the intent but taking a different path to implementing that intent. The behavior added by categories is a compile-time artifact, and is not something dynamically acquired. Moreover, categories do not encapsulate an instance of the class being extended.
Appleseed, John Doe, Jane Smith, Bob Warwick, Kate 
#import "XYZPerson.h"
@interface XYZPerson (XYZPersonNameDisplayAdditions) - (NSString *)lastNameFirstNameString; @end 
#import "XYZPerson+XYZPersonNameDisplayAdditions.h"
@implementation XYZPerson (XYZPersonNameDisplayAdditions) - (NSString *)lastNameFirstNameString {
return [NSString stringWithFormat:@"%@, %@", self.lastName, self.firstName]; }
@end
Once you’ve declared a category and implemented the methods, you can use those methods from any instance of the class, as if they were part of the original class interface: 
#import "XYZPerson+XYZPersonNameDisplayAdditions.h"
@implementation SomeObject - (void)someMethod {
XYZPerson *person = [[XYZPerson alloc] initWithFirstName:@"John" lastName:@"Doe"];
XYZShoutingPerson *shoutingPerson = [[XYZShoutingPerson alloc] initWithFirstName:@"Monica"
lastName:@"Robinson"];

NSLog(@"The two people are %@ and %@",
[person lastNameFirstNameString], [shoutingPerson lastNameFirstNameString]); }
@end

25. What is Delegation in iOS?
Delegation is a design pattern in which one object sends messages to another object—specified as its delegate—to ask for input or to notify it that an event is occurring. Delegation is often used as an alternative to class inheritance to extend the functionality of reusable objects. For example, before a window changes size, it asks its delegate whether the new size is ok. The delegate replies to the window, telling it that the suggested size is acceptable or suggesting a better size. (For more details on window resizing, see thewindowWillResize:toSize: message.)
Delegate methods are typically grouped into a protocol. A protocol is basically just a list of methods. The delegate protocol specifies all the messages an object might send to its delegate. If a class conforms to (or adopts) a protocol, it guarantees that it implements the required methods of a protocol. 

(Protocols may also include optional methods).In this application, the application object tells its delegate that the main startup routines have finished by sending it theapplicationDidFinishLaunching: message. The delegate is then able to perform additional tasks if it wants. 
26. How can we achieve singleton pattern in iOS? 
The Singleton design pattern ensures a class only has one instance, and provides a global point of access to it. The class keeps track of its sole instance and ensures that no other instance can be created. Singleton classes are appropriate for situations where it makes sense for a single object to provide access to a global resource.Several Cocoa framework classes are singletons. They includeNSFileManager, NSWorkspace, NSApplication, and, in UIKit,UIApplication. A process is limited to one instance of these classes. When a client asks the class for an instance, it gets a shared instance, which is lazily created upon the first request.

27.What is delegate pattern in iOS?
Delegation is a mechanism by which a host object embeds a weak reference (weak in the sense that it’s a simple pointer reference, unretained) to another object—its delegate—and periodically sends messages to the delegate when it requires its input for a task. The host object is generally an “off-the-shelf” framework object (such as an NSWindow or NSXMLParserobject) that is seeking to accomplish something, but can only do so in a generic fashion. The delegate, which is almost always an instance of a custom class, acts in coordination with the host object, supplying program-specific behavior at certain points in the task (see Figure 4-3). Thus delegation makes it possible to modify or extend the behavior of another object without the need for subclassing.Refer: delegate pattern

28.What are all the difference between categories and subclasses?Why should we go to subclasses? 
Category is a feature of the Objective-C language that enables you to add methods (interface and implementation) to a class without having to make a subclass. There is no runtime difference—within the scope of your program—between the original methods of the class and the methods added by the category. The methods in the category become part of the class type and are inherited by all the class’s subclasses.As with delegation, categories are not a strict adaptation of the Decorator pattern, fulfilling the intent but taking a different path to implementing that intent. 
The behavior added by categories is a compile-time artifact, and is not something dynamically acquired. Moreover, categories do not encapsulate an instance of the class being extended.The Cocoa frameworks define numerous categories, most of them informal protocols . Often they use categories to group related methods. You may implement categories in your code to extend classes without subclassing or to group related methods. 
However, you should be aware of these caveats: You cannot add instance variables to the class. If you override existing methods of the class, your application may behave unpredictably. 
29.What is notification in iOS? 
The notification mechanism of Cocoa implements one-to-many broadcast of messages based on the Observer pattern. Objects in a program add themselves or other objects to a list of observers of one or more notifications, each of which is identified by a global string (the notification name). The object that wants to notify other objects—the observed object—creates a notification object and posts it to a notification center. The notification center determines the observers of a particular notification and sends the notification to them via a message. The methods invoked by the notification message must conform to a certain single-parameter signature. The parameter of the method is the notification object, which contains the notification name, the observed object, and a dictionary containing any supplemental information.Posting a notification is a synchronous procedure. The posting object doesn’t regain control until the notification center has broadcast the notification to all observers. For asynchronous behavior, you can put the notification in a notification queue; control returns immediately to the posting object and the notification center broadcasts the notification when it reaches the top of the queue.Regular notifications—that is, those broadcast by the notification center—are
intraprocess only. If you want to broadcast notifications to other processes, you can use the istributed notification center and its related API. 
30.What is the difference between delegates and notifications?
We can use notifications for a variety of reasons. For example, you could broadcast a notification to change how user-interface elements display information based on a certain event elsewhere in the program. Or you could use notifications as a way to ensure that objects in a document save their state before the document window is closed. The general purpose of notifications is to inform other objects of program events so they can respond appropriately.But objects receiving notifications can react only after the event has occurred. This is a significant difference from delegation. The delegate is given a chance to reject or modify the operation proposed by the delegating object. Observing objects, on the other hand, cannot directly affect an impending operation. 

.......PART 2......COMING SOON.....

Thursday 19 September 2013

SQLite Demo

1. Project Requirements
I suggest that you have at least a basic understanding of SQLite, writing SQL statements, the XCode interface and using the terminal in OSX. If you don’t know anything about any of these topics then this tutorial probably isn’t for you.


2. Creating our SQLite database for our tutorial
We first need to create a database for use with our application. For the purposes of this tutorial we will be building a database of animals along with a little information on them and a picture.
Fire up a new Terminal window and make a new folder to store the database in, here are the commands I ran


cd /Users/lookaflyingdonkey/Documents
mkdir SQLiteTutorial
cd SQLiteTutorial
sqlite3 AnimalDatabase.sql


You should now be at a “sqlite” command prompt, this is where we will be building our database structure and entering some test data.
For our example we need the name of the animal, a short description and a link to an image. Follow the commands below to create the table and to enter some sample data.

CREATE TABLE animals ( id INTEGER PRIMARY KEY, name VARCHAR(50), description TEXT, image VARCHAR(255) );

INSERT INTO animals (name, description, image) VALUES ('Elephant', 'The elephant is a very large animal that lives in Africa and Asia', 'http://dblog.com.au/wp-content/elephant.jpg');
INSERT INTO animals (name, description, image) VALUES ('Monkey', 'Monkies can be VERY naughty and often steal clothing from unsuspecting tourists', 'http://dblog.com.au/wp-content/monkey.jpg');
INSERT INTO animals (name, description, image) VALUES ('Galah', 'Galahs are a wonderful bird and they make a great pet (I should know, I have one)', 'http://dblog.com.au/wp-content/galah.jpg');
INSERT INTO animals (name, description, image) VALUES ('Kangaroo', 'Well I had to add the Kangaroo as they are the essence of the Australian image', 'http://dblog.com.au/wp-content/kangaroo.jpg');


The first command will create the table with the required structure and the next four will insert some test data for us to work with. To ensure that you have entered the data correctly you can execute “SELECT * FROM animals;” and see if it returns the items above. Once you are confident that everything had been created successfully you can leave the sqlite command line by typing “.quit”.


3. Creating our Project
Now that our database is all ready to go we need to setup our X-Code project.
Start off by creating a new “Empty Application”.

Give your Project a name, I called mine “SQLiteTutorial”.

Right Click on the “Supporting Files” folder in the left hand pane and click “Add File”, we want to create a new “ViewController”.


4. Adding SQLite Framework and our Animal Database
Now that we have created all of our views and classes it is time to start the real grunt work.
First we need to include the SQLite libraries so our application can utilise them. To do this you will need to click on the project name in the left hand pane, then click on “Targets > Build Phases > Link binaries… > click on plus signand add  libsqlite3.0.dylib” 

We also need to add our database we created earlier . To do this simply right click on the “Supporting Files” , click “Add > Existing Files…”, navigate to the location you created the database in then double click on the AnimalDatabase.sql file. Another popup will appear, just click add.
All done with the importing, time to code!


5. The Coding begins!
We are going to start the coding by building our “Animal” object, every animal will have 3 properties, a name, a description and an image URL.
Open up the “Animal.h” file from the “Classes” folder and edit its contents to look like below,

#import <UIKit/UIKit.h>

@interface Animal : NSObject {
NSString *name;
NSString *description;
NSString *imageURL;
}

@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


Most of the above code should be pretty familiar to you, the only thing that may not be is the initWithName line, this line will allow us 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 Animal Object, open up the “Animal.m” file and edit its contents to look like below:


#import "Animal.h"

@implementation Animal
@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 should be pretty easy to read as well, it basically stores the supplied data from the initWithName function and return the object (self).
Now its time to setup the Application delegate to access the database.
Open up the “SQLiteTutorialAppDelegate.h” and edit its contents to look like below:

#import <UIKit/UIKit.h>
#import <sqlite3.h> // Import the SQLite database framework

@interface SQLiteTutorialAppDelegate : NSObject  {

    UIWindow *window;
    UINavigationController *navigationController;

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

// Array to store the animal objects
NSMutableArray *animals;
}

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

@end


What we are doing here is importing the SQLite database framework and creating some variables for storing the database details and an array of animal objects.
Now open up the “SQLiteTutorialAppDelegate.m” file and edit its contents to look like below:


#import "SQLiteTutorialAppDelegate.h"
#import "RootViewController.h"
#import "Animal.h" // Import the animal object header

@implementation SQLiteTutorialAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize animals; // Synthesize the aminals array

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Setup some globals
databaseName = @"AnimalDatabase.sql";

// 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 animal records and construct the "animals" array
[self readAnimalsFromDatabase];

// Configure and show the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}

- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}

- (void)dealloc {
[animals release];
[navigationController release];
[window release];
[super dealloc];
}

-(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) readAnimalsFromDatabase {
// Setup the database object
sqlite3 *database;

// Init the animals Array
animals = [[NSMutableArray alloc] init];

// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from animals";
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 animal object with the data from the database
Animal *animal = [[Animal alloc] initWithName:aName description:aDescription url:aImageUrl];

// Add the animal object to the animals Array
[animals addObject:animal];

[animal release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

}
sqlite3_close(database);

}

@end


Now I know that may look like a fair bit of code and it probably also looks quite scary! But really it is quite simple and I have tried to comment nearly every line to describe to you what the line does and why it is there.
The checkAndCreateDatabase function checks to see if we have already copied our database from the application bundle to the users filesystem (in their documents folder), if the database hasn’t already been created or it has been removed for some reason it will be recreated from the default database.
Next the readAnimalsFromDatabase function will make a connection to the database that is stored in the users documents folder, and then executes the SQL statement “SELECT * FROM animals”. It will then go through each row that is returned and it will extract the name, description and imageURL from the result and build an Animal object for each. You will see the “sqlite3_column_text” function used here, there are many more of these for returning other field types such as “sqlite3_column_int” for integers, “sqlite3_column_blob” for blobs or “sqlite3_column_value” to get an unknown value.
Now that we have the data in our array and we have it in our known format we are ready to start displaying it.
Open up the “RootViewController.m” file and edit the numberOfRowsInSection to look like the following:


SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
return appDelegate.animals.count;

What this does is it creates a link to the application delegate, and then the second line returns the size f the animals array in out Application delegate, this array was filled previously from the SQLite database.
Now in the cellForRowAtIndexPath function you will need at change it to look like the following:


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    // Set up the cell
    SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animal *animal = (Animal *)[appDelegate.animals objectAtIndex:indexPath.row];

[cell setText:animal.name];
return cell;
}


We pretty much just added 3 lines under the “// Set up the cell” line, the first one is the same as we added previously to access the application delegate. The second line creates a new Animal object based on the array from the application delegate, it will be used to create a row for each individual record in the database. On the final line we are just setting the text of the cell to the name field from the Animal object.

You can now run the program and you should see a table view with the 4 animals we added to the database, if you added more than my default animals you should see them in here as well.
We will now setup the AnimalViewController, open up the “AnimalViewController.h” file and edit its contents to below:


#import <UIKit/UIKit.h>

@interface AnimalViewController : UIViewController {
IBOutlet UITextView *animalDesciption;
IBOutlet UIImageView *animalImage;
}

@property (nonatomic, retain) IBOutlet UITextView *animalDesciption;
@property (nonatomic, retain) IBOutlet UIImageView *animalImage;

@end


What we are doing above is adding an outlet for the description and image for the Animal, we will use these later on when we link the view up.
Now open up the “AnimalViewController.m” file and add a synthesize call for for the description and image, this will go under the “@implementation AnimalViewController” line, like so:


#import "AnimalViewController.h"

@implementation AnimalViewController

@synthesize animalDesciption, animalImage;


Now it is time to make the detailed view page appear when you select a record. Open up the “AnimalViewController.xib” file from the resources folder and the interface builder should appear.
The first thing we need to do is to set the File’s Owner Class to AnimalViewController, this is done by selecting the “File’s Owner” item in the main window and then clicking Tools > Identity Inspector in the top menu, and then selecting AnimalViewController from the class dropdown.
Your inspector window should now look like this:

We are going to be using a UITextView for the description (as it will allow for word wrapping and scrolling in the case that the description is quite large) and a UIImageView to display the image.


Now that we have everything laid out it is time to link them all up, start by holding control and click+drag from the “File’s Owner” to the “View” objects, a little gray menu will appear and you will need to select view. Now hold control and click+drag from the “File’s Owner” to the UITextView in the layout window, you should see “animalDescription” in the popup list, select it. Repeat this process for the UIImageView and you should see animalImage appear, select it also.
Now save the interface and close the interface builder.
Nearly done! All we have to do now is to setup the code for when a user presses on a record in the table view.
Open up the “RootViewController.h” file and edit its contents to below:


#import <UIKit/UIKit.h>
#import "AnimalViewController.h"

@interface RootViewController : UITableViewController {
AnimalViewController *animalView;
}

@property(nonatomic, retain) AnimalViewController *animalView; 

@end


We are creating an instance of the AnimalViewController to be used bu the RootViewController when a user presses on an item.
Now open up the “RootViewController.m” file and edit the top part of the file to look like below:


#import "RootViewController.h"
#import "SQLiteTutorialAppDelegate.h"
#import "Animal.h"

@implementation RootViewController
@synthesize animalView;

This will just synthesize the animalView that we just added.
First up lets set the default title of our view, to do this you need to uncomment the viewDidLoad function, and edit it to below:


- (void)viewDidLoad {
    [super viewDidLoad];
    // Uncomment the following line to add the Edit button to the navigation bar.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

self.title = @"My Zoo";
}


We also need to edit the didSelectRowAtIndexPath
function in this file, edit it to look like below:


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic -- create and push a new view controller
SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animal *animal = (Animal *)[appDelegate.animals objectAtIndex:indexPath.row];

if(self.animalView == nil) {
AnimalViewController *viewController = [[AnimalViewController alloc] initWithNibName:@"AnimalViewController" bundle:nil];
self.animalView = viewController;
[viewController release];
}


// Setup the animation
[self.navigationController pushViewController:self.animalView animated:YES];
// Set the title of the view to the animal's name
self.animalView.title = [animal name];
// Set the description field to the animals description
[self.animalView.animalDesciption setText:[animal description]];
// Load the animals image into a NSData boject and then assign it to the UIImageView
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[animal imageURL]]];
UIImage *animalImage = [[UIImage alloc] initWithData:imageData cache:YES];
self.animalView.animalImage.image = animalImage;

}


What we are doing here is checking to see if the animalView object has already been created, if not then create it.
The next few lines are used to setup the animation (slide from right to left) and to set the actual data fields to those of the selected animal.
Now you should be ready to fire up the application and see it in all its glory.
You should see your windows looking like below.



5. Project Files

Here are the source files for this project: Download the project source files

Wednesday 12 December 2012

NSAttributedString in iOS 6


infoString=@"This is an example of Attributed String";



NSMutableAttributedString *attString=[[NSMutableAttributedString allocinitWithString:infoString];
NSInteger _stringLength=[infoString length];

UIColor *_black=[UIColor blackColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, _stringLength)];



               









UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:3.0range:NSMakeRange(0, _stringLength)];















UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-3.0range:NSMakeRange(0, _stringLength)];

















UIColor *_red=[UIColor redColor];
UIColor *_green=[UIColor greenColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_green range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-3.0]range:NSMakeRange(0, _stringLength)];



















UIColor *_green=[UIColor greenColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];

NSShadow *shadowDic=[[NSShadow allocinit];
[shadowDic setShadowBlurRadius:5.0];
[shadowDic setShadowColor:[UIColor grayColor]];
[shadowDic setShadowOffset:CGSizeMake(03)];
              
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_green range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSShadowAttributeName value:shadowDic range:NSMakeRange(0, _stringLength)];
                



















UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
  [attString addAttribute:NSForegroundColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];              
  [attString addAttribute:NSKernAttributeName value:[NSNumber numberWithInt:5range:NSMak








UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:2range:NSMakeRange(0, _stringLength)];








UIColor *_blue=[UIColor blueColor];
UIColor *_blueL=[UIColor colorWithRed:0 green:0 blue:0.5 alpha:0.7];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
                
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_blue range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSBackgroundColorAttributeName value:_blueL range:NSMakeRange(020)];


                





iHope this helped you :)