iOS:Interview Questions Part II

1. What is difference between shallow copying and deep copying?

  • Object copying can be shallow or deep. Both shallow- and deep-copy approaches directly duplicate scalar properties but differ on how they handle pointer references, particularly references to objects (for example, NSString *str). A deep copy duplicates the objects referenced while a shallow copy duplicates only the references to those objects.
  • Example : if object A is shallow-copied to object B, object B refers to the same instance variable (or property) that object A refers to. Deep-copying objects is preferred to shallow-copying, especially with value objects.
  • Example: Object A has property NSString *testProperty .If Object A is shallow copied to Object B,both will refer to same property NSString *testProperty.If Object A is deep – copied to Object B , then both will have their own copies of NSString *testProperty.
  • Memory Management:Like object creation, object copying returns an object with a retain count of 1. In memory-managed code, the client copying the object is responsible for releasing the copied object. Copying an object is similar in purpose to retaining an object in that both express an ownership in the object. However, a copied object belongs exclusively to the new owner, who can mutate it freely, while a retained object is shared between the owners of the original object and clients who have retained the object.

Refer : Object Copying 

2.  What is difference between atomic and nonatomic properties?

3.  Is Objective C a runtime language?

  • The Objective-C language defers as many decisions as it can from compile time and link time to runtime. Whenever possible, it does things dynamically. This means that the language requires not just a compiler, but also a runtime system to execute the compiled code. The runtime system acts as a kind of operating system for the Objective-C language; it’s what makes the language work.

Refer: Objective C Runtime

4. What is difference between NSNotification and protocol?

5. What is difference between method and selector?

6. What is difference between Categories and Extensions ?

iOS : Disable ARC for non-ARC files in ARC projects

To disable ARC for selected files add the -fno-objc-arc compiler flag to those files.

  • Add compiler flags in Targets -> Build Phases -> Compile Sources.
  • You have to double click on the right column of the row under Compiler Flags.
  •  You can also add it to multiple files by holding the cmd button to select the files and then pressing enter to bring up the flag edit box

iOS: Interview Questions Part I

1. What are Categories and Extensions?
  • category allows you to add methods to an existing class—even to one for which you do not have the source. Categories are a powerful feature that allows you to extend the functionality of existing classes without subclassing. Using categories, you can also distribute the implementation of your own classes among several files.
2. What are protocols ?
Protocols declare methods that can be implemented by any class. Protocols are useful in at least three situations:
  • To declare methods that others are expected to implement.
  • To declare the interface to an object while concealing its class.
  • To capture similarities among classes that are not hierarchically related.
Refer : Protocols
3. What is a Singleton class ?
  • A singleton class returns the same instance no matter how many times an application requests it.A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.
  • You obtain the global instance from a singleton class through a factory method. The class lazily creates its sole instance the first time it is requested and thereafter ensures that no other instance can be created. A singleton class also prevents callers from copying, retaining, or releasing the instance

Refer : Singleton Class

4. What is lazy loading?
5.  What is fast enumeration?

Core Data: Retrieving Values from core data entity

Code to fetch the data from core data.

//--------------------------------------------------------------------------------
// get data from database

+(NSArray*)getDataFromDB:(NSString*)table_name
{
NSManagedObjectContext *context = [(MisoUIV3AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:table_name

inManagedObjectContext:context];

[fetchRequest setEntity:entity];

NSError *error;

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

[fetchRequest release];

return fetchedObjects;

}

iOS: Check for internet connectivity

In order to check wether your iOS device is connected to internet or not, we can use the sample code provided by Apple.

The Reachability class code can be found over here (Apple Developer’s documentation):

http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2

Here is a small snippet to use reachability class:

- (BOOL) isReachable

{

Reachability *r = [Reachability reachabilityWithHostName:@"google.com"];

NetworkStatus internetStatus = [r currentReachabilityStatus];

if(internetStatus == NotReachable) return NO;

else return YES;

}

You can customize the reachability message.You can pop up an alert for user .The alert can inform user to check for internet.

NSString* msg = "Please check your internet connection"
- (BOOL) isReachable:(NSString *) msg
{
Reachability *r = [Reachability reachabilityWithHostName:@"google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable)
{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];

[Alert show];
[Alert release];
return NO;

}
else
{
return YES;
}
}

iOS: Core Data Model Version – Create New version and Set Current Version

XCODE 4
Create New version

  • Select project.xcdatamodeld from Project Navigation Area
  • Click on Editor -> Add Model Version
  • Enter The new model version
  • Click Finish

Set Current Version:

  • Select project.xcdatamodeld (Top Level data model file)
  • Click on View – > Utilities -> Show Object library (To make utilities panel visible)
  • Under Utilities Panel (rightmost side) -> Version Core Data Model
  • Under Version Core Data model -> Current : change the drop down to the model version you want to set active.

iOS: Steps for deploying build on your iPhone

It happens with me.. I don’t know wether it happens with you too?
It takes hell lot of time to figure out ways to do a simple task… so here are the steps of deploying build/app on your iphone..
1. Attach the phone to your computer and open iTunes
2. Unzip the folder containing build and provisioning profile.
3. Drag and drop the .app folder and .mobileprovision file into the applications window of your iTunes.
4. To make sure, the provision file has been installed correctly, drag and drop just the mobile provisioning file into the applications window of your iTunes again.
5. Click on your iPhone link in the left navigation menu and select the Applications tab.
6. Make sure the application is selected in the Application list and hit sync.

Creativity in computing .. “Tickle Inside Technology outside”

A tickle makes me laugh when it catches me unaware. It’s a funny feeling I don’t completely understand. But tickles, the funny sensations, are not just related to my external being as I often find myself being tickled in my brain. The unwanted tickle causes an itch, which makes me take action involuntarily.

Tickles inside our mind can force us to think, to imagine and cause enough irritation to make us take actions that we otherwise won’t dare to do.

Popularly, creativity has been associated with the people from the art world, painters, dancers or musicians. The common trait among them being their thought process that is adapted to boundary less imagination. But creativity is not really limited to the domain of these few fields. Browsing through the history of technology and computing, there are innumerable incidents representing technologists becoming leaders when they married their technological depth to their peripheral understanding of some distant fields. Some of the innovative products and services are presented below in order to elicit this fact.

Creativity happens when we allow ourselves to make mistakes. The ideal way for an organization to be creative is to not just look to the experts, but allow explorers (people who have a passion to explore and those who are not afraid of making mistakes) to make decisions once in a while.

This notion led the Interaction design Guru Alan Cooper to reverse the trend of programming of interactions. Earlier interactions between software and humans were designed by programmers. But the problem lay in that they always designed programs, not products. They designed their code such that it ran more efficiently and could be easily worked upon by other engineering professionals. But the design that Alan Cooper does or that happens at IDEO is very different. Teams at these companies are concerned about Product Design and the interaction that the software has with humans, assuring that human users do not get frustrated with the product and actually end up being delighted. They design products outside in, rather than from inside out. This methodology sets them apart, and is the reason that they are leaders in creative consulting.

The potential of realizing imagination, realizing dreams lies in the simple question: ‘Are we ready to take risks?”.

In the past, people have had ideas that would in their time be considered absurd, but have turned out to be immensely successful and game changing. That is because creativity is a funny thing. The more absurd the thought, the more potential it carries to be creative. Some people just feel these thoughts (resulting from needs) tickle in their brain and around their neck. And just like the sweat it keeps irritating them until they are realized.

Peter Burns, the talented designer of iPod iWatch created his idea during his universities days. While jogging, he used to hate using the standard iPod headphones. He thought there must be a better way to strap on/hold your iPod. So he twisted, substituted, combined, modified and had put the iPod in different use, and now he calls it iWatch.

Doug Engelbart, father of the mouse, realized that problem solvers required the ability to interact with information displays using some sort of device to move [a cursor] around the screen. There were several devices then in use, or being considered for use: the light pen, joysticks, etc. but the best and efficient device was missing. This need ‘tickled’ Doug Engelbart and the technology which bought a revolution in the world of computing, the mouse, was born.

Ray Tomlinson gave society one of the greatest communication tools in history. He was not sure about what he was doing. It was a hack. It probably took five-six hours to create the technology. The idea cropped by observing the facility that had proved its usefulness in sending messages to the same computer. It stuck to him: What about when someone was on another computer, maybe across the country? It would be like the telephone but they wouldn’t have to be there to answer the phone. This idea on implementation gave us our first email.

‘Innovation best comes from people who know nothing about the topic’.

Steven J Sasson (inventor of the digital camera), has very beautifully portrayed the hidden reason behind the innovative ideas in the above statement. With his boundary less imagination and playing with the given tool he created the first digital camera which bought revolution in the world of photography. He was given a charge-coupled device. It was a brand new device and he was asked to do some imaging experiments. Not really knowing what to do, he decided to make an image-capture device, made it portable and he came up with the idea of building a digital camera, different from the conventional camera that existed then. He just adapted an analogist’s way to take pictures, he was no photography expert. I would again call it the ‘tickle’ in his brain, that helped him make the connection, the connection between the previously unconnected elements. When a thing is molded, twisted or related with seemingly unrelated it generates something new and innovative.

At the end I would like to quote words from Abraham Maslow:

The key question isn’t “What fosters creativity?” But it is why in God’s name isn’t everyone creative? Where was the human potential lost? How was it crippled? I think therefore a good question might be not why do people create? But why do people not create or innovate? We have got to abandon that sense of amazement in the face of creativity, as if it were a miracle if anybody created anything.

I think it’s time that more of us let the tickles inside our brains to take control of us, to bring our technology thoughts to the outside world, to be ready to take risks and venture into creating the worlds that we at present only imagine.

Perl Script to scrape log files and enter in Database

If its a small company or a midsize project,this simple post might help you out…
This is what it does (code snippets added at the end of the post):

Download logs from your FTP -> Scan them and put the relevant info in database -> Create a webpage to query database and display the output.

Resources:

1> Perl Script

- Connects to FTP
- Downloads Access Log files
- Pattern matching to extract the relevant data
- Insert the relavant data into database.

2> MYSQL Database

- Stores the data send by Perl script
- SQL queries as requested by PHP page

3> PHP Page

- Displays the data requested by firing queries on MYSQL database.

So here we go:

Perl Script:

-Mac users be happy,  perl is preinstalled on mac but for windows you have to follow the whole procedure of setting up perl,apache,mysql.. which can be painful at times.

Here is my Google search:

- Code

http://www.goldb.org/remotebackup.html
http://perl.about.com/od/filesystem/qt/perlglob.htm
http://www.cs.cf.ac.uk/Dave/PERL/node241.html

-MYSQL Database

Perl uses DBI and DBD connectors to connect to MySql Database.MySql is not preinstalled on Mac so you can follow these links… might help you out.

http://www.abbeyworkshop.com/howto/osx/osxMysqlInstall/index.html
http://developer.apple.com/internet/opensource/osdb.html
http://www.quicomm.com/apm_dbddbi.html
http://www.cpan.org/modules/by-category/07_Database_Interfaces/DBD/

- PHP
http://maestric.com/doc/mac/apache_php_mysql_snow_leopard

#!/usr/bin/perl
use DBI;
use Net::FTP;
# connect
my $dbh = DBI->connect("DBI:mysql:database=log_db;host=localhost", "root","", {'RaiseError' => 1})or die "Cannot connect to the DB: $DBI::errstr\n" ;

# Get the maximum date
my $sth = $dbh->prepare("select max(logDate) from iphonePHP");
$sth->execute;
while(@row = $sth->fetchrow_array())
{
print "$row[0]";
$year_db = substr($row[0],0,4);
print "year db:".$year_db."\n";
$month_db = substr($row[0],5,2);
print "month_db:".$month_db."\n";
$date_db = substr($row[0],8,2);
print "day:".$date_db."\n";
}

$date_db = ($date_db+1);
if($date_db = 10 )
{
$LOGFILE = "access_log.".$year_db."-".$month_db."-".$date_db;
}
if($date_db == 29 && ($month ==2) && !($year_db %400 ==0 || ($year_db %100 != 0 && $year_db %4 == 0)))
{
$date_db = 1;
$month_db = $month_db + 1;
if($month_db < 10)
{
$LOGFILE = "access_log.".$year_db."-"."0".$month_db."-"."0".$date_db;
}
else
{
$LOGFILE = "access_log.".$year_db."-".$month_db."-"."0".$date_db;
}

}
if($date_db == 30 && ($month == 2)&& ($year_db %400 ==0 || ($year_db %100 != 0 && $year_db %4 == 0)))
{
$date_db = 1;
$month_db = $month_db + 1;
if($month_db < 10)
{
$LOGFILE = "access_log.".$year_db."-"."0".$month_db."-"."0".$date_db;
}
else
{
$LOGFILE = "access_log.".$year_db."-".$month_db."-"."0".$date_db;
}
}
if($date_db == 31 && (($month_db == 4)|| ($month_db == 6) || ($month_db == 9)|| ($month_db == 1)))
{
$date_db = 1;
$month_db = $month_db + 1;
if($month_db < 10)
{
$LOGFILE = "access_log.".$year_db."-"."0".$month_db."-"."0".$date_db;
}
else
{
$LOGFILE = "access_log.".$year_db."-".$month_db."-"."0".$date_db;
};
}
if($date_db == 32)
{
$date_db = 1;
$month_db = $month_db + 1;
if($month_db new("02e6818.netsolhost.com", Debug => 0)
or die "Cannot connect to some.host.name: $@";
$ftp->login("$login","$password")
or die "Cannot login ", $ftp->message;

$ftp->get($LOGFILE)
or die "get failed ", $ftp->message;
$ftp->quit;
print "filename: downloaded".$LOGFILE."\n";

$log_date = substr($LOGFILE,11,10);
print "LOG DATE:".$log_date."\n";

open(LOGFILE) or die("Could not open log file.");
foreach $line ()
{
$w = "(.+?)";
$line =~ m/^$w $w $w \[$w:$w $w\] "$w $w $w" $w $w "$w" "$w"/;

$site = $1;
$logName = $2;
$fullName = $3;
$date = $4;
$time = $5;
$gmt = $6;
$req = $7;
$file = $8;
$proto = $9;
$status = $10;
$length = $11;
$referal = $12;
$user_ag = $13;

# do line-by-line processing.
if ($file =~ m/NylonLive\/new.php/)
{
#print $req.$file."\n";
my $sth = $dbh->prepare(qq{insert into iphonePHP SET ip=?, getRequest=?,magzine_name="NYLON",logDate=?,logTime=?,status=?,length=?,referal=?,user_link=?});
$sth->execute($site,$req.$file,$log_date,$time,$status,$length,$referal,$user_ag) or $dbh->errstr;

}

elsif ($file =~ m/NylonRIM\/index.php/)
{
#print $req.$file."\n";
my $sth = $dbh->prepare(qq{insert into rimPHP SET ip=?, getRequest=?,magzine_name="NYLON",logDate=?,logTime=?,status=?,length=?,referal=?,user_link=?});
$sth->execute($site,$req.$file,$log_date,$time,$status,$length,$referal,$user_ag) or $dbh->errstr;
}
elsif ($file =~ m/NylonLive\/AndroidMZN.php/)
{
#print $req.$file."\n";
my $sth = $dbh->prepare(qq{insert into androidPHP SET ip=?, getRequest=?,magzine_name="NYLON",logDate=?,logTime=?,status=?,length=?,referal=?,user_link=?});
$sth->execute($site,$req.$file,$log_date,$time,$status,$length,$referal,$user_ag) or $dbh->errstr;
}
elsif ($file =~ m/instant_mozine\/getWWE.php/)
{
# print $req.$file."\n";
my $sth = $dbh->prepare(qq{insert into iphonePHP SET ip=?, getRequest=?,magzine_name="WWE",logDate=?,logTime=?,status=?,length=?,referal=?,user_link=?});
$sth->execute($site,$req.$file,$log_date,$time,$status,$length,$referal,$user_ag) or $dbh->errstr;
}
elsif ($file =~ m/instant_mozine\/getWWEdroid.php/)
{
#print $req.$file."\n";
my $sth = $dbh->prepare(qq{insert into androidPHP SET ip=?, getRequest=?,magzine_name="WWE",logDate=?,logTime=?,status=?,length=?,referal=?,user_link=?});
$sth->execute($site,$req.$file,$log_date,$time,$status,$length,$referal,$user_ag) or $dbh->errstr;
}

}

print $referal."\n";
print $user_ag."\n";
close(LOGFILE);
# clean up
$dbh->disconnect();

p.s: post is not completed yet