Wednesday, December 30, 2009

Clang Static Analyzer for iPhone Programming


Scan Analyzer : Clang Analyzer LLVM Compiler


Overview:


While we may be familiar with using tools likes Instruments to find and fix memory leaks in our application, the Clang Static Analyzer takes a different approach to memory leak detection by compiling our Xcode project and scanning each method, class, loop and logic block for potential leaks.

We may heard of Clang Static Analyzer referred to by the name of command line tool used to run the analyzer:scan-build.


Requirements


Download the Clang/LLVM Static Analyzer from http://clang-analyzer.llvm.org/ and click the link for checker-NNN.tar.bz2 (Latest build (Universal binary, 10.5+): checker-230.tar.bz2 (built December 8, 2009) ).



Installation


1) We are going to install the check-NNN binary in Mac /usr/local/bin folder. Run the following command to verify that this folder exists:

sudo mkdir -p /usr/local/bin


2) Open Terminal.app from the Application folders, and move the contents of checker-NNN to the usr/local/bin folder(here NNN is 230 version no.)

sudo mv ~/Downloads/checker-230/* /usr/local/bin



Basic Usage


scan- build tests our code by compiling our Xcode project and studying it for defects during the build process. Initially, we are required to change some of the settings in our XcodeProject.

  1. Select the xcodeproject group, and click on Get Info.

  2. In General tabs, select “Base SDK” - “iPhone Simulator 3.0”

  3. In Build tab, select “Base SDK” - iPhonesimulator3.0” & Valid Architectures – i386.

  4. Make Code Signing Identity - “Don't Code Sign”

  5. Select “Any iPhone OS Device” - “Don't Code Sign”

    And then

To check our code, we just invoke scan-build from the command line at the top level of any one of your project directories.

  1. Still in Terminal.app, change into one of your project directories

  2. Run scan-build of your Xcode project.

scan-build -k -V xcodebuild -configuration Debug -s iphonesimulator3.0

Customizing your Output Report

After running scan-build for sometimes, the first thing you might want to do is tell scan-build to put its report in a different place. To do that, simply specify the output folder on the command line like so:

scan-build -o /custompath/for/report xcodebuild -configuration Debug -s iphonesimulator3.0


  • If you are using iphone SDK 3.0 on Snow Leapord, then Clang Static Analyzer is coming in-built in the IDE.

It will be great to use it for better programming analysis to judge the memory management.

Thanks

Tuesday, August 18, 2009

Cocoa with JSON data using SBJSon

Hi all,

This is my very first blog. For this blog, I would like to thank to Stig Brautaset for bringing out an excellent JSON Parser " SBJSON".
Firstly download SBJSON framework from

There are two ways to include SBJSON framework into the code.

1) Either include this framework into the framework folder of the application

2) Or Copy all the classes into 1 folder in Classes folder.

Here are the list of the classes available in SBJSON framework


"SBJSON.h"

"NSObject+SBJSON.h"

"NSString+SBJSON.h"

"SBJsonParser.h"

"SBJsonWriter.h"

"SBJsonBase.h"


And in all these

------

"SBJSON.h"

"NSObject+SBJSON.h"

"NSString+SBJSON.h"

------


the above 3 classes are only imported in JSON.h file


And now import JSON.h file into the class, where we are going to communicate through the HTTP JSON response into Cocoa.



Now I am going to share the way to interact with the server for GET request


1)

- (NSMutableArray *) downloadGetData:(NSString *)urlString

{

id response = [self objectWithGetUrl:[NSURL URLWithString:[NSString stringWithFormat:@"%@" ,urlString]]];

NSMutableArray *record = (NSMutableArray *)response;

return record;

}


Here we are taking the URL in string where we want to hit, to get the response, will call the method objectWithGetUrl:(NSURL*)type to get the response of the type id assigning it the value into NSURL format by converting the string into NSURL.




2)

- (id) objectWithGetUrl:(NSURL *)url

{

SBJSON *jsonParser = [SBJSON new];

NSString *jsonString = [self stringWithGetUrl:url];

// Parse the JSON into an Object

id data = [jsonParser objectWithString:jsonString error:NULL];

//Release SBJSon Object

[jsonParser release];

return data;

}


Here, Create a SBJSON object to parse JSON into a native Cocoa object using [SBJSON new]. This object will be in autorelease pool ( it means, it will automatically loose its memory when it will be not in scope).
These we will call the the local method stringWithGetUrl. and the url parameter which we have got in this method will be assign to stringWithGetUrl's parameter.

Then using the JSONParser class

- (NSString *)stringWithGetUrl:(NSURL *)url

{

@try {

NSInteger internetConnectionAvailability = [self internetConnectionAvailable];

if(internetConnectionAvailability == kInternetConnectionAvailable)

{

NSInteger timeInterval = [NSLocalizedString(@"Time Interval", @"Time Interval") intValue];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url

cachePolicy:NSURLRequestReturnCacheDataElseLoad

timeoutInterval:timeInterval];

// Fetch the JSON response

NSData *urlData;

NSURLResponse *response;

NSError *error;

// Make synchronous request

urlData = [NSURLConnection sendSynchronousRequest:urlRequest

returningResponse:&response

error:&error];

if([urlData length] == 0)

{

UIAlertView *alertTest = [[UIAlertView alloc]

initWithTitle:@"Sorry !"

message:@"No Service is available"

delegate:self

cancelButtonTitle:@"OK"

otherButtonTitles:nil];

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

[alertTest show];

[alertTest autorelease];

return @"";

}

else {

return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];

}

// Construct a String around the Data from the response

}

}

@catch (NSException * e)

{

NSString *msg = [NSString stringWithFormat:@"%@",[e description]];

NSLog(@"hi NSException %@",[e description]);

UIAlertView *errorAlertView = [[[UIAlertView alloc] initWithTitle:@"Exception !" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:nil,nil] autorelease];

[errorAlertView show];

}

@finally

{

}

return @"";

}


Here we have requested the url with Get type request, and getting the result into byte format, and then we will convert it into NSString, the json String, which we are converting to JSON using json parser.


Now here, we will discuss, how could we request the URL with type POST and sending JSON data in request

@try

{

if([self internetConnectionAvailable] == kInternetConnectionAvailable)

{

SBJSON *jsonParser = [SBJSON new];

jsonParser.humanReadable = YES;

NSString *jsonString = [NSString stringWithFormat:@"%@", [refinements JSONFragment], nil];

NSString *changeJSON = [NSString stringWithFormat:@"%@", [refinements JSONFragment], nil];

#ifdef TARGET_IPHONE_SIMULATOR

NSLog(jsonString);

#endif

changeJSON = [NSString stringWithFormat:@"categoryId=%@&refinements=%@",categoryId,changeJSON];

NSData *requestData = [NSData dataWithBytes: [changeJSON UTF8String] length: [changeJSON length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:[NSString stringWithFormat: @"%@results", ServerUrl]]];

NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];

[request setHTTPMethod: @"POST"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setHTTPBody: requestData];

//Data returned by WebService

NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];

NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

categorySearchList = (NSMutableDictionary*) [jsonParser objectWithString:returnString error:NULL];

[[GlobalObjects sharedInstance] setCategorySearchList:categorySearchList];

[jsonParser release];

[request release];

request = nil;

[returnString release];

returnString = nil;

[[GlobalObjects sharedInstance] setCategorySearchList:categorySearchList];

[NSThread detachNewThreadSelector:@selector(saveResultForCategoryinCache) toTarget:self withObject:nil];

}

}

@catch (NSException * e)

{

NSString *msg = [NSString stringWithFormat:@"%@",[e description]];

NSLog(@"hi NSException %@",[e description]);

UIAlertView *errorAlertView = [[[UIAlertView alloc] initWithTitle:@"Exception !" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:nil,nil] autorelease];

[errorAlertView show];

}

@finally

{

}