- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Add the navigation controller's view to the window and display.
[NSThread detachNewThreadSelector:@selector(scheduleLocalNotifications) toTarget:self withObject:nil];
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
return YES;
}
-(void) scheduleLocalNotifications{
for (int i = 0; i < 60; i++)
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
NSDate *sleepDate = [[NSDate date] dateByAddingTimeInterval:i * 60];
NSLog(@"Sleepdate is: %@", sleepDate);
localNotif.fireDate = sleepDate;
NSLog(@"fireDate is %@",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"This is local notification %i"), i];
localNotif.alertAction = NSLocalizedString(@"View Details", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
NSLog(@"scheduledLocalNotifications are %@", [[UIApplication sharedApplication] scheduledLocalNotifications]);
[localNotif release];
}
}
Friday, November 11, 2011
Local notifcication at regular interval
Monday, October 10, 2011
Uploading XML to server via PHP
XCODE CODE
_____________________
// #######################################################
// Uploading to .net SERVER #######################################################
// #######################################################
//
NSString *urlString = @"http://www.innokria.com/dotnet.php";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"0xLhTaLbOkNdArZ"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//Reading the file
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"readme.xml"];
NSData *myData = [NSData dataWithContentsOfFile:Read];
NSLog(@"file exist at %@",myData);
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dotnet\"; filename=\"test.xml\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:myData];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSError *returnError = nil;
NSHTTPURLResponse *returnResponse = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnResponse error:&returnError];
##################################
in php , make a empty folder called dotnets and upload this php page
_______________dotnet.php
$uploaddir = './dotnets/';
$file = basename($_FILES['dotnet']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['dotnet']['tmp_name'], $uploadfile)) {
echo "http://www.innokria.com/dotnet/{$file}";
}
?>
_____________________
// #######################################################
// Uploading to .net SERVER #######################################################
// #######################################################
//
NSString *urlString = @"http://www.innokria.com/dotnet.php";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"0xLhTaLbOkNdArZ"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//Reading the file
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"readme.xml"];
NSData *myData = [NSData dataWithContentsOfFile:Read];
NSLog(@"file exist at %@",myData);
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dotnet\"; filename=\"test.xml\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:myData];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSError *returnError = nil;
NSHTTPURLResponse *returnResponse = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnResponse error:&returnError];
##################################
in php , make a empty folder called dotnets and upload this php page
_______________dotnet.php
$uploaddir = './dotnets/';
$file = basename($_FILES['dotnet']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['dotnet']['tmp_name'], $uploadfile)) {
echo "http://www.innokria.com/dotnet/{$file}";
}
?>
Friday, September 30, 2011
sending email in obj-c
in.h
import MessageUI/MessageUI.h
delegate MFMailComposeViewControllerDelegate
- (void)openInAppEmail:(NSArray*)recipients
mailSubject:(NSString*)mailSubject
mailBody:(NSString*)mailBody
isHtml:(BOOL)isHtml;
##########################################
in .m
- (IBAction)mail:(id)sender {
// SMS * start = [[SMS alloc] initWithNibName:@"SMS" bundle:[NSBundle mainBundle]];
//start.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
// start.modalPresentationStyle = UIModalPresentationFormSheet;
// [self presentModalViewController:start animated:YES];
email=@"hi@hi.com";
[self openInAppEmail:[NSArray arrayWithObject:email] mailSubject:@"" mailBody:@"" isHtml:YES];
}
- (void)openInAppEmail:(NSArray*)recipients
mailSubject:(NSString*)mailSubject
mailBody:(NSString*)mailBody
isHtml:(BOOL)isHtml
{
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setToRecipients:recipients];
[controller setSubject:mailSubject];
[controller setMessageBody:mailBody isHTML:isHtml];
[self presentModalViewController:controller animated:YES];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error {
[self dismissModalViewControllerAnimated:YES];
}
import MessageUI/MessageUI.h
delegate MFMailComposeViewControllerDelegate
- (void)openInAppEmail:(NSArray*)recipients
mailSubject:(NSString*)mailSubject
mailBody:(NSString*)mailBody
isHtml:(BOOL)isHtml;
##########################################
in .m
- (IBAction)mail:(id)sender {
// SMS * start = [[SMS alloc] initWithNibName:@"SMS" bundle:[NSBundle mainBundle]];
//start.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
// start.modalPresentationStyle = UIModalPresentationFormSheet;
// [self presentModalViewController:start animated:YES];
email=@"hi@hi.com";
[self openInAppEmail:[NSArray arrayWithObject:email] mailSubject:@"" mailBody:@"" isHtml:YES];
}
- (void)openInAppEmail:(NSArray*)recipients
mailSubject:(NSString*)mailSubject
mailBody:(NSString*)mailBody
isHtml:(BOOL)isHtml
{
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setToRecipients:recipients];
[controller setSubject:mailSubject];
[controller setMessageBody:mailBody isHTML:isHtml];
[self presentModalViewController:controller animated:YES];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error {
[self dismissModalViewControllerAnimated:YES];
}
Thursday, September 29, 2011
marker in core -Plot
// OHLC plot
CPTMutableLineStyle *whiteLineStyle = [CPTMutableLineStyle lineStyle];
whiteLineStyle.lineColor = [CPTColor whiteColor];
whiteLineStyle.lineWidth = 1.0f;
CPTTradingRangePlot *ohlcPlot = [[[CPTTradingRangePlot alloc] initWithFrame:graph.bounds] autorelease];
ohlcPlot.identifier = @"OHLC";
ohlcPlot.lineStyle = whiteLineStyle;
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
whiteTextStyle.fontSize = 48.0;
ohlcPlot.labelTextStyle = whiteTextStyle;
ohlcPlot.labelOffset = 5.0;
ohlcPlot.stickLength = 2.0f;
ohlcPlot.dataSource = self;
ohlcPlot.plotStyle = CPTTradingRangePlotStyleOHLC;
[graph addPlot:ohlcPlot];
CPTMutableLineStyle *whiteLineStyle = [CPTMutableLineStyle lineStyle];
whiteLineStyle.lineColor = [CPTColor whiteColor];
whiteLineStyle.lineWidth = 1.0f;
CPTTradingRangePlot *ohlcPlot = [[[CPTTradingRangePlot alloc] initWithFrame:graph.bounds] autorelease];
ohlcPlot.identifier = @"OHLC";
ohlcPlot.lineStyle = whiteLineStyle;
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
whiteTextStyle.fontSize = 48.0;
ohlcPlot.labelTextStyle = whiteTextStyle;
ohlcPlot.labelOffset = 5.0;
ohlcPlot.stickLength = 2.0f;
ohlcPlot.dataSource = self;
ohlcPlot.plotStyle = CPTTradingRangePlotStyleOHLC;
[graph addPlot:ohlcPlot];
Sunday, September 4, 2011
NSSCANNER take out String and numbers
NSString *str = @" hello i am emp 1313 object of string class 123";
NSScanner *scanner = [NSScanner scannerWithString:str];
// set it to skip non-numeric characters
[scanner setCharactersToBeSkipped:
[[NSCharacterSet decimalDigitCharacterSet]
invertedSet]];
int i;
while ([scanner scanInt:&i])
{
NSLog(@"Found int: %d",i);
}
// reset the scanner to skip numeric characters
[scanner setScanLocation:0];
[scanner setCharactersToBeSkipped:
[NSCharacterSet decimalDigitCharacterSet]];
NSString *resultString;
while ([scanner scanUpToCharactersFromSet:
[NSCharacterSet decimalDigitCharacterSet]
intoString:&resultString]) {
NSLog(@"Found string: %@",resultString);
}
Friday, September 2, 2011
save and update data / Read and Write
-(NSString *)readFile:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSError *error= NULL;
id resultData=[NSString stringWithContentsOfFile:appFile encoding:NSUTF8StringEncoding error:&error];
if (error == NULL)
{
return resultData;
}
}
return NULL;
}
-(void)writeFile:(NSString *)fileName dataArray:(NSArray *)data
{
NSMutableString *dataString=[NSMutableString stringWithString:@""];
for (int i=0; i<[data count]; i++)
{
if (i == [data count]-1)
{
[(NSMutableString *)dataString appendFormat:@"%@",[data objectAtIndex:i]];
}
else
{
[(NSMutableString *)dataString appendFormat:@"%@\n",[data objectAtIndex:i]];
}
}
[self writeFile:fileName data:dataString];
}
-(void)writeFile:(NSString *)fileName data:(id)data
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error=NULL;
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSString *fileString=[NSString stringWithContentsOfFile:appFile encoding:NSUTF8StringEncoding error:&error];
data=[data stringByAppendingFormat:@"\n%@",fileString];
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
else
{
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
if (error != NULL)
{
//Check Error Here. if any.
}
}
- (IBAction)save:(id)sender {
//To Write the File.
NSArray *array=[NSArray arrayWithObjects:usernameField.text,passwordField.text, nil];
[self writeFile:@"arra.txt" dataArray:array];
//Read the File
NSString *result=[self readFile:@"arra.txt"];
NSArray *outputArray=[result componentsSeparatedByString:@"\n"];
for (int i=0; i<[outputArray count]; i++)
{
NSLog(@"the output=%@ index=%i",[outputArray objectAtIndex:i], i);
}
}
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSError *error= NULL;
id resultData=[NSString stringWithContentsOfFile:appFile encoding:NSUTF8StringEncoding error:&error];
if (error == NULL)
{
return resultData;
}
}
return NULL;
}
-(void)writeFile:(NSString *)fileName dataArray:(NSArray *)data
{
NSMutableString *dataString=[NSMutableString stringWithString:@""];
for (int i=0; i<[data count]; i++)
{
if (i == [data count]-1)
{
[(NSMutableString *)dataString appendFormat:@"%@",[data objectAtIndex:i]];
}
else
{
[(NSMutableString *)dataString appendFormat:@"%@\n",[data objectAtIndex:i]];
}
}
[self writeFile:fileName data:dataString];
}
-(void)writeFile:(NSString *)fileName data:(id)data
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error=NULL;
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSString *fileString=[NSString stringWithContentsOfFile:appFile encoding:NSUTF8StringEncoding error:&error];
data=[data stringByAppendingFormat:@"\n%@",fileString];
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
else
{
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
if (error != NULL)
{
//Check Error Here. if any.
}
}
- (IBAction)save:(id)sender {
//To Write the File.
NSArray *array=[NSArray arrayWithObjects:usernameField.text,passwordField.text, nil];
[self writeFile:@"arra.txt" dataArray:array];
//Read the File
NSString *result=[self readFile:@"arra.txt"];
NSArray *outputArray=[result componentsSeparatedByString:@"\n"];
for (int i=0; i<[outputArray count]; i++)
{
NSLog(@"the output=%@ index=%i",[outputArray objectAtIndex:i], i);
}
}
Thursday, August 25, 2011
Dyanamic adding and removing buttons
#### button Adding
- (IBAction)whisky:(id)sender {
if(j<21) {
CGRect rect = CGRectMake(100,20,70,20);
lbl1= [[[UILabel alloc] initWithFrame:rect] autorelease];
NSString *intString = [NSString stringWithFormat:@"%d", j-10];
[lbl1 setText:intString]; lbl1.tag=99; [self.view addSubview:lbl1];
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self action:@selector(ratingAction2:)forControlEvents:UIControlEventTouchUpInside];
[button3 setBackgroundImage:[UIImage imageNamed:@"scanbutton1.png"] forState:UIControlStateNormal]; button3.tag = j;
button3.backgroundColor = [UIColor blueColor];
button3.frame = CGRectMake(120, width1, 35, 35);
[self.view addSubview:button3]; width1 = width1 -38; j++;
}
}
############### button delete based on tag ###########
- (IBAction)delWhis:(id)sender { if(j>1)
{
j--;
int f;
f=j;
[[self.view viewWithTag:f] removeFromSuperview];
//int b = button3.tag/10;
{
NSLog(@" whisky ration is %d",f);
width1 = width1 +38;
}
}
}
Dynamic button and Event on them ( Retro)
- (IBAction)Can:(id)sender {
i++;
UIButton *button2;
//view did load
// for( i= 1;i<=5;i++)
{
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:@selector(ratingAction:)forControlEvents:UIControlEventTouchUpInside];
[button2 setBackgroundImage:[UIImage imageNamed:@"scanbutton1.png"] forState:UIControlStateNormal];
button2.tag = i;
button2.backgroundColor = [UIColor clearColor];
button2.frame = CGRectMake(20, width, 35, 35);
[self.view addSubview:button2];
width = width -38;
}
NSLog(@" i am can ");
// [self dismissModalViewControllerAnimated:YES];
}
-(void)ratingAction:(id*)sender
{
if ([sender isKindOfClass:[UIButton class]]) {
UIButton *temp=(UIButton*)sender;
if ([temp tag]==1 || [temp tag]==3 || [temp tag]==6 || [temp tag]==7 ) {
[temp setBackgroundColor:[UIColor redColor]];
}
}
}
i++;
UIButton *button2;
//view did load
// for( i= 1;i<=5;i++)
{
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:@selector(ratingAction:)forControlEvents:UIControlEventTouchUpInside];
[button2 setBackgroundImage:[UIImage imageNamed:@"scanbutton1.png"] forState:UIControlStateNormal];
button2.tag = i;
button2.backgroundColor = [UIColor clearColor];
button2.frame = CGRectMake(20, width, 35, 35);
[self.view addSubview:button2];
width = width -38;
}
NSLog(@" i am can ");
// [self dismissModalViewControllerAnimated:YES];
}
-(void)ratingAction:(id*)sender
{
if ([sender isKindOfClass:[UIButton class]]) {
UIButton *temp=(UIButton*)sender;
if ([temp tag]==1 || [temp tag]==3 || [temp tag]==6 || [temp tag]==7 ) {
[temp setBackgroundColor:[UIColor redColor]];
}
}
}
Tuesday, August 23, 2011
Android Installation
Download Andriod SDK and Eclispse
2) Launch Eclipse
3) go to help -> install new software
4) enter this url
http : //dl-ssl.google.com/Android/eclipse/
5)and configure
6) then create a new project (Others) and select google api and then launch first app
2) Launch Eclipse
3) go to help -> install new software
4) enter this url
http : //dl-ssl.google.com/Android/eclipse/
5)and configure
6) then create a new project (Others) and select google api and then launch first app
Monday, August 15, 2011
MD5 in Xcode
import --> #import CommonCrypto/CommonDigest.h
then make a Class Utility
in .h
#import Foundation/Foundation.h
#import CommonCrypto/CommonDigest.h
@interface Utilities : NSObject {
}
//generates md5 hash from a string
+ (NSString *) returnMD5Hash:(NSString*)concat;
@end
##############################################################
in .m
#import "Utilities.h"
@implementation Utilities
//generate md5 hash from string
+ (NSString *) returnMD5Hash:(NSString*)concat {
const char *concat_str = [concat UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(concat_str, strlen(concat_str), result);
NSMutableString *hash = [NSMutableString string];
for (int i = 0; i < 16; i++)
[hash appendFormat:@"%02X", result[i]];
return [hash lowercaseString];
}
@end
#######################
in the main Class
NSString *myMD5String = [Utilities returnMD5Hash:@"test"];
NSLog(@" myMD5String ----------------------- %@",myMD5String);
And Its Done , Happy Coding :)
then make a Class Utility
in .h
#import Foundation/Foundation.h
#import CommonCrypto/CommonDigest.h
@interface Utilities : NSObject {
}
//generates md5 hash from a string
+ (NSString *) returnMD5Hash:(NSString*)concat;
@end
##############################################################
in .m
#import "Utilities.h"
@implementation Utilities
//generate md5 hash from string
+ (NSString *) returnMD5Hash:(NSString*)concat {
const char *concat_str = [concat UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(concat_str, strlen(concat_str), result);
NSMutableString *hash = [NSMutableString string];
for (int i = 0; i < 16; i++)
[hash appendFormat:@"%02X", result[i]];
return [hash lowercaseString];
}
@end
#######################
in the main Class
NSString *myMD5String = [Utilities returnMD5Hash:@"test"];
NSLog(@" myMD5String ----------------------- %@",myMD5String);
And Its Done , Happy Coding :)
Tuesday, July 26, 2011
Thursday, July 21, 2011
Core data Basics -Part 1
Welcome to the world of core data
________________________________________
step 1) import core data framework
step 2) create a coredata object -> Test.xcdatamodeld
create entity -> Class
Create Attributes-> Name , Descrioptin;
step3) in AppDelegate class add these
NSManagedObjectContext *managedObjectContext_;
NSManagedObjectModel *managedObjectModel_;
NSPersistentStoreCoordinator *persistentStoreCoordinator_;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory;
- (void)saveContext;
###################################################
______________ in App delegate.m____________________________
#pragma mark -
#pragma mark Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext_ != nil) {
return managedObjectContext_;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext_ = [[NSManagedObjectContext alloc] init];
[managedObjectContext_ setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext_;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel_ != nil) {
return managedObjectModel_;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel_;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Test.sqlite"];
NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator_;
}
#pragma mark -
#pragma mark Application's Documents directory
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#################################
_______________ in VeiwControll.h___
step5) create text fields to enter user values
UITextField* nameTextField;
UITextField* descriptionTextField;
UITextView* ingredientsTextView;
}
@property (nonatomic,retain) IBOutlet UITextField* nameTextField;
@property (nonatomic,retain) IBOutlet UITextField* descriptionTextField;
@property (nonatomic,retain) IBOutlet UITextView* ingredientsTextView;
##################
_______________in VC.m_____________
step6) to save the data in Sqlite
- (IBAction)save:(id)sender {
CoreData_rahul_saveDataAppDelegate* delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* managedObjectContext = delegate.managedObjectContext;
NSManagedObject *nam;
nam=[NSEntityDescription insertNewObjectForEntityForName:@"Class" inManagedObjectContext:managedObjectContext];
[nam setValue:nameTextField.text forKey:@"Name"];
[nam setValue:descriptionTextField.text forKey:@"Desciption"];
NSError* error;
[managedObjectContext save:&error];
[self fetchRecords]; // to show data in console
}
step 7) to display data in console we use Fetch Request
- (void)fetchRecords {
CoreData_rahul_saveDataAppDelegate* delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* managedObjectContext = delegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Class" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);
//You were leaking your request here
[request release], request = nil;
//The following line is redundant. You are leaking an array here
//NSMutableArray *namesArray = [[NSMutableArray alloc]init];
NSArray *namesArray = [events valueForKey:@"Name"];
NSLog(@"array us %@",namesArray);
}
Thanks
________________________________________
step 1) import core data framework
step 2) create a coredata object -> Test.xcdatamodeld
create entity -> Class
Create Attributes-> Name , Descrioptin;
step3) in AppDelegate class add these
NSManagedObjectContext *managedObjectContext_;
NSManagedObjectModel *managedObjectModel_;
NSPersistentStoreCoordinator *persistentStoreCoordinator_;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory;
- (void)saveContext;
###################################################
______________ in App delegate.m____________________________
#pragma mark -
#pragma mark Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext_ != nil) {
return managedObjectContext_;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext_ = [[NSManagedObjectContext alloc] init];
[managedObjectContext_ setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext_;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel_ != nil) {
return managedObjectModel_;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel_;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Test.sqlite"];
NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator_;
}
#pragma mark -
#pragma mark Application's Documents directory
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#################################
_______________ in VeiwControll.h___
step5) create text fields to enter user values
UITextField* nameTextField;
UITextField* descriptionTextField;
UITextView* ingredientsTextView;
}
@property (nonatomic,retain) IBOutlet UITextField* nameTextField;
@property (nonatomic,retain) IBOutlet UITextField* descriptionTextField;
@property (nonatomic,retain) IBOutlet UITextView* ingredientsTextView;
##################
_______________in VC.m_____________
step6) to save the data in Sqlite
- (IBAction)save:(id)sender {
CoreData_rahul_saveDataAppDelegate* delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* managedObjectContext = delegate.managedObjectContext;
NSManagedObject *nam;
nam=[NSEntityDescription insertNewObjectForEntityForName:@"Class" inManagedObjectContext:managedObjectContext];
[nam setValue:nameTextField.text forKey:@"Name"];
[nam setValue:descriptionTextField.text forKey:@"Desciption"];
NSError* error;
[managedObjectContext save:&error];
[self fetchRecords]; // to show data in console
}
step 7) to display data in console we use Fetch Request
- (void)fetchRecords {
CoreData_rahul_saveDataAppDelegate* delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* managedObjectContext = delegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Class" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);
//You were leaking your request here
[request release], request = nil;
//The following line is redundant. You are leaking an array here
//NSMutableArray *namesArray = [[NSMutableArray alloc]init];
NSArray *namesArray = [events valueForKey:@"Name"];
NSLog(@"array us %@",namesArray);
}
Thanks
Tuesday, July 19, 2011
Monday, July 11, 2011
retain and Copy diff
In a general setting, retaining an object will increase its retain count by one. This will help keep the object in memory and prevent it from being blown away. What this means is that if you only hold a retained version of it, you share that copy with whomever passed it to you.
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
Wednesday, June 29, 2011
Convert Char to NsString and vice versa
char to NsString
char *a = "Testing";
NSString *aa = [NSString stringWithCString: (const char *)a encoding: NSASCIIStringEncoding];NSLog(@"%@", aa);
#############################################
NSString to c char
char * c_string = [someNSString UTF8String];
char *a = "Testing";
NSString *aa = [NSString stringWithCString: (const char *)a encoding: NSASCIIStringEncoding];NSLog(@"%@", aa);
#############################################
NSString to c char
char * c_string = [someNSString UTF8String];
Wednesday, June 22, 2011
@selectors in obj-c
elector in Objective C
In short, Selector can either be a name of method or a message to an object when used in the source code. And SEL is the complied form of a Selector.
- (void) fooNoInputs {
NSLog(@"Does selector test");
}
- (void) fooOneInput:(NSString*) first {
// NSLog(@"Does selector test");
NSLog(@"my slectore Logs %@", first);
}
- (void)viewDidLoad
{
//
//##############################################################################
// SELCETOR test
//##############################################################################
[self performSelector:@selector(fooNoInputs)];
[self performSelector:@selector(fooOneInput:) withObject:@"firstc"];
############## difference between
[self playButtonSound]; &
[self performSelector:@selector(playButtonSound)];
Both to the same thing, but [self playButtonSound]; is definitely the normal way to invoke a method in Objective-C. However, using performSelector: allows you to call a method that is only determined at runtime.
In short, Selector can either be a name of method or a message to an object when used in the source code. And SEL is the complied form of a Selector.
- (void) fooNoInputs {
NSLog(@"Does selector test");
}
- (void) fooOneInput:(NSString*) first {
// NSLog(@"Does selector test");
NSLog(@"my slectore Logs %@", first);
}
- (void)viewDidLoad
{
//
//##############################################################################
// SELCETOR test
//##############################################################################
[self performSelector:@selector(fooNoInputs)];
[self performSelector:@selector(fooOneInput:) withObject:@"firstc"];
############## difference between
[self playButtonSound]; &
[self performSelector:@selector(playButtonSound)];
Both to the same thing, but [self playButtonSound]; is definitely the normal way to invoke a method in Objective-C. However, using performSelector: allows you to call a method that is only determined at runtime.
@property in objc
Property attributes are special keywords to tell compiler how to generate the getters and setters. Here you specify two property attributes: nonatomic, which tells the compiler not to worry about multithreading, and retain, which tells the compiler to retain the passed-in variable before setting the instance variable.
In other situations, you might want to use the “assign” property attribute instead of retain, which tells the compiler NOT to retain the passed-in variable. Or perhaps the “copy” property attribute, which makes a copy of the passed-in variable before setting.
In other situations, you might want to use the “assign” property attribute instead of retain, which tells the compiler NOT to retain the passed-in variable. Or perhaps the “copy” property attribute, which makes a copy of the passed-in variable before setting.
Sunday, June 19, 2011
Categories in obj-c
// Base Class
@interface ClassA : NSObject
- (NSString *) myMethod;
@end
@implementation ClassA
- (NSString*) myMethod { return @"A"; }
@end
//Category
@interface ClassA (CategoryB)
- (NSString *) myMethod;
@end
@implementation ClassA (CategoryB)
- (NSString*) myMethod { return @"B"; }
@end
Calling the method "myMethod" after including the category nets the result "B".
@interface ClassA : NSObject
- (NSString *) myMethod;
@end
@implementation ClassA
- (NSString*) myMethod { return @"A"; }
@end
//Category
@interface ClassA (CategoryB)
- (NSString *) myMethod;
@end
@implementation ClassA (CategoryB)
- (NSString*) myMethod { return @"B"; }
@end
Calling the method "myMethod" after including the category nets the result "B".
Friday, June 3, 2011
Php + XML package
//ob_start();
if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") )
{ header("Content-type: application/xhtml+xml;charset=utf-8"); }
else { header("Content-type: text/xml;charset=utf-8"); }
echo "\n";
// Write Code here
ob_get_contents();
//?>
if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") )
{ header("Content-type: application/xhtml+xml;charset=utf-8"); }
else { header("Content-type: text/xml;charset=utf-8"); }
echo "\n";
// Write Code here
ob_get_contents();
//?>
Sunday, May 29, 2011
function with diff parameter
Objective-C program with multiple parameter
Objective-C enables programmer to use method with multiple parameter. These parameter can be of same type or of different type.
This is a sample program that shows sum of three numbers as output.
MyClass.h
#import
@interface MyClass:NSObject{
}
// declare method for more than one parameter
-(int) sum: (int) a andb: (int) b andc:(int)c;
@end
MyClass.m
#import
#import"MyClass.h"
@implementation MyClass
-(int) sum: (int) a andb: (int) b andc:(int)c;{
return a+b+c;
}
@end
MyClass.m
#import
#import"MyClass.m"
int main(){
MyClass *class = [[MyClass alloc]init];
printf("Sum is : %d",[class sum : 5 andb : 6 andc:10]);
[class release];
return ;
}
source rose india
Objective-C enables programmer to use method with multiple parameter. These parameter can be of same type or of different type.
This is a sample program that shows sum of three numbers as output.
MyClass.h
#import
@interface MyClass:NSObject{
}
// declare method for more than one parameter
-(int) sum: (int) a andb: (int) b andc:(int)c;
@end
MyClass.m
#import
#import"MyClass.h"
@implementation MyClass
-(int) sum: (int) a andb: (int) b andc:(int)c;{
return a+b+c;
}
@end
MyClass.m
#import
#import"MyClass.m"
int main(){
MyClass *class = [[MyClass alloc]init];
printf("Sum is : %d",[class sum : 5 andb : 6 andc:10]);
[class release];
return ;
}
source rose india
Monday, May 23, 2011
Difference betwen protocol and category
A protocol is the same thing as an interface in Java: it's essentially a contract that says, "Any class that implements this protocol will also implement these methods."
A category, on the other hand, just binds methods to a class. For example, in Cocoa, I can create a category for NSObject that will allow me to add methods to the NSObject class (and, of course, all subclasses), even though I don't really have access to NSObject.
To summarize: a protocol specifies what methods a class will implement; a category adds methods to an existing class.
The proper use of each, then, should be clear: Use protocols to declare a set of methods that a class must implement, and use categories to add methods to an existing class.
A category, on the other hand, just binds methods to a class. For example, in Cocoa, I can create a category for NSObject that will allow me to add methods to the NSObject class (and, of course, all subclasses), even though I don't really have access to NSObject.
To summarize: a protocol specifies what methods a class will implement; a category adds methods to an existing class.
The proper use of each, then, should be clear: Use protocols to declare a set of methods that a class must implement, and use categories to add methods to an existing class.
Delete Row in UITableView
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{ NSLog(@"matrix is her%@",appDelegate.favDetail);
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[appDelegate.favDetail removeObjectAtIndex: indexPath.row];
[tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject: indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
}
{ NSLog(@"matrix is her%@",appDelegate.favDetail);
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[appDelegate.favDetail removeObjectAtIndex: indexPath.row];
[tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject: indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
}
Wednesday, May 18, 2011
NSDate and time seperate
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSLog(@"\n"
"theDate: |%@| \n"
"theTime: |%@| \n"
, theDate, theTime);
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSLog(@"\n"
"theDate: |%@| \n"
"theTime: |%@| \n"
, theDate, theTime);
Adding LibXML and OpenSSL to Xcode
header search path-> $(SDKROOT)/usr/include/libxml2
2) include any folder like iPhoneSimulator4.2.sdk and add this name
2) include any folder like iPhoneSimulator4.2.sdk and add this name
Thursday, May 5, 2011
make car c++
{ // car body
b2PolygonDef poly1, poly2;
// bottom half
poly1.vertexCount = 5;
poly1.vertices[4].Set(-2.2f,-0.74f);
poly1.vertices[3].Set(-2.2f,0);
poly1.vertices[2].Set(1.0f,0);
poly1.vertices[1].Set(2.2f,-0.2f);
poly1.vertices[0].Set(2.2f,-0.74f);
poly1.filter.groupIndex = -1;
poly1.density = 20.0f;
poly1.friction = 0.68f;
poly1.filter.groupIndex = -1;
// top half
poly2.vertexCount = 4;
poly2.vertices[3].Set(-1.7f,0);
poly2.vertices[2].Set(-1.3f,0.7f);
poly2.vertices[1].Set(0.5f,0.74f);
poly2.vertices[0].Set(1.0f,0);
poly2.filter.groupIndex = -1;
poly2.density = 5.0f;
poly2.friction = 0.68f;
poly2.filter.groupIndex = -1;
b2BodyDef bd;
bd.position.Set(-35.0f, 5.8f);
m_vehicle = m_world->CreateBody(&bd);
m_vehicle->CreateShape(&poly1);
m_vehicle->CreateShape(&poly2);
m_vehicle->SetMassFromShapes();
}
{ // vehicle wheels
b2CircleDef circ;
circ.density = 40.0f;
circ.radius = 0.38608f;
circ.friction = 0.8f;
circ.filter.groupIndex = -1;
b2BodyDef bd;
bd.allowSleep = false;
bd.position.Set(-33.8f, 5.0f);
m_rightWheel = m_world->CreateBody(&bd);
m_rightWheel->CreateShape(&circ);
m_rightWheel->SetMassFromShapes();
bd.position.Set(-36.2f, 5.0f);
m_leftWheel = m_world->CreateBody(&bd);
m_leftWheel->CreateShape(&circ);
m_leftWheel->SetMassFromShapes();
}
{ // join wheels to chassis
b2Vec2 anchor;
b2RevoluteJointDef jd;
jd.Initialize(m_vehicle, m_leftWheel, m_leftWheel->GetWorldCenter());
jd.collideConnected = false;
jd.enableMotor = true;
jd.maxMotorTorque = 10.0f;
jd.motorSpeed = 0.0f;
m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
jd.Initialize(m_vehicle, m_rightWheel, m_rightWheel->GetWorldCenter());
jd.collideConnected = false;
m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
}
{ // ground
b2PolygonDef box;
box.SetAsBox(11.5f, 0.5f);
box.friction = 0.62f;
#pragma mark plank height
b2BodyDef bd;
bd.position.Set(-26.0f, 4.8f);
b2Body* ground = m_world->CreateBody(&bd);
ground->CreateShape(&box);
}
b2PolygonDef poly1, poly2;
// bottom half
poly1.vertexCount = 5;
poly1.vertices[4].Set(-2.2f,-0.74f);
poly1.vertices[3].Set(-2.2f,0);
poly1.vertices[2].Set(1.0f,0);
poly1.vertices[1].Set(2.2f,-0.2f);
poly1.vertices[0].Set(2.2f,-0.74f);
poly1.filter.groupIndex = -1;
poly1.density = 20.0f;
poly1.friction = 0.68f;
poly1.filter.groupIndex = -1;
// top half
poly2.vertexCount = 4;
poly2.vertices[3].Set(-1.7f,0);
poly2.vertices[2].Set(-1.3f,0.7f);
poly2.vertices[1].Set(0.5f,0.74f);
poly2.vertices[0].Set(1.0f,0);
poly2.filter.groupIndex = -1;
poly2.density = 5.0f;
poly2.friction = 0.68f;
poly2.filter.groupIndex = -1;
b2BodyDef bd;
bd.position.Set(-35.0f, 5.8f);
m_vehicle = m_world->CreateBody(&bd);
m_vehicle->CreateShape(&poly1);
m_vehicle->CreateShape(&poly2);
m_vehicle->SetMassFromShapes();
}
{ // vehicle wheels
b2CircleDef circ;
circ.density = 40.0f;
circ.radius = 0.38608f;
circ.friction = 0.8f;
circ.filter.groupIndex = -1;
b2BodyDef bd;
bd.allowSleep = false;
bd.position.Set(-33.8f, 5.0f);
m_rightWheel = m_world->CreateBody(&bd);
m_rightWheel->CreateShape(&circ);
m_rightWheel->SetMassFromShapes();
bd.position.Set(-36.2f, 5.0f);
m_leftWheel = m_world->CreateBody(&bd);
m_leftWheel->CreateShape(&circ);
m_leftWheel->SetMassFromShapes();
}
{ // join wheels to chassis
b2Vec2 anchor;
b2RevoluteJointDef jd;
jd.Initialize(m_vehicle, m_leftWheel, m_leftWheel->GetWorldCenter());
jd.collideConnected = false;
jd.enableMotor = true;
jd.maxMotorTorque = 10.0f;
jd.motorSpeed = 0.0f;
m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
jd.Initialize(m_vehicle, m_rightWheel, m_rightWheel->GetWorldCenter());
jd.collideConnected = false;
m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
}
{ // ground
b2PolygonDef box;
box.SetAsBox(11.5f, 0.5f);
box.friction = 0.62f;
#pragma mark plank height
b2BodyDef bd;
bd.position.Set(-26.0f, 4.8f);
b2Body* ground = m_world->CreateBody(&bd);
ground->CreateShape(&box);
}
make bridge C++
#pragma mark bridge
b2Body* ground = NULL;
{
b2PolygonDef sd;
sd.SetAsBox(0.2f, 0.1f);
b2BodyDef bd;
bd.position.Set(0.0f, 0.0f);
ground = m_world->CreateBody(&bd);
ground->CreateShape(&sd);
}
{
b2PolygonDef sd;
sd.SetAsBox(0.5f, 0.125f);
sd.density = 20.0f;
sd.friction = 0.2f;
b2RevoluteJointDef jd;
const int32 numPlanks = 30;
b2Body* prevBody = ground;
for (int32 i = 0; i < numPlanks; ++i)
{
b2BodyDef bd;
bd.position.Set(-14.5f + 1.0f * i, 5.0f);
b2Body* body = m_world->CreateBody(&bd);
body->CreateShape(&sd);
body->SetMassFromShapes();
b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f);
jd.Initialize(prevBody, body, anchor);
m_world->CreateJoint(&jd);
prevBody = body;
}
b2Vec2 anchor(-15.0f + 1.0f * numPlanks, 5.0f);
jd.Initialize(prevBody, ground, anchor);
m_world->CreateJoint(&jd);
}
b2Body* ground = NULL;
{
b2PolygonDef sd;
sd.SetAsBox(0.2f, 0.1f);
b2BodyDef bd;
bd.position.Set(0.0f, 0.0f);
ground = m_world->CreateBody(&bd);
ground->CreateShape(&sd);
}
{
b2PolygonDef sd;
sd.SetAsBox(0.5f, 0.125f);
sd.density = 20.0f;
sd.friction = 0.2f;
b2RevoluteJointDef jd;
const int32 numPlanks = 30;
b2Body* prevBody = ground;
for (int32 i = 0; i < numPlanks; ++i)
{
b2BodyDef bd;
bd.position.Set(-14.5f + 1.0f * i, 5.0f);
b2Body* body = m_world->CreateBody(&bd);
body->CreateShape(&sd);
body->SetMassFromShapes();
b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f);
jd.Initialize(prevBody, body, anchor);
m_world->CreateJoint(&jd);
prevBody = body;
}
b2Vec2 anchor(-15.0f + 1.0f * numPlanks, 5.0f);
jd.Initialize(prevBody, ground, anchor);
m_world->CreateJoint(&jd);
}
Tuesday, May 3, 2011
Basics Pointer
if a is a struct use a.b
if a is a pointer to a struct use a->b
if a is an object pointer and b is a ivar use a->b
if a is an object pointer and b is a property use a
if a is a pointer to a struct use a->b
if a is an object pointer and b is a ivar use a->b
if a is an object pointer and b is a property use a
Monday, May 2, 2011
Struct in ObjC
// in interface
struct fruit {
int a;
};
// in implementation
int main()
{
struct fruit apple;
apple.a = 1;
return 0;
}
struct fruit {
int a;
};
// in implementation
int main()
{
struct fruit apple;
apple.a = 1;
return 0;
}
Tuesday, April 5, 2011
UINavigation back pop View Controller
-(void)goBack:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
//[self.navigationController popToRootViewControllerAnimated:YES];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
#pragma mark back buttonw
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 55, 30);
[button setImage:[UIImage imageNamed:@"backButton.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* btBack = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = btBack;
}
{
[self.navigationController popViewControllerAnimated:YES];
//[self.navigationController popToRootViewControllerAnimated:YES];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
#pragma mark back buttonw
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 55, 30);
[button setImage:[UIImage imageNamed:@"backButton.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* btBack = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = btBack;
}
Thursday, March 24, 2011
set default zoom level in UIScrollview
- (void)viewDidLoad {
imageView= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"KK_Map-02.jpg"]];
//self.imageView = imageView;
//[tempImageView release];
[super viewDidLoad];
//aWw.delegate = self;
//[scrollView setUserInteractionEnabled:YES];
scrollView.contentSize = CGSizeMake(imageView.frame.size.width, imageView.frame.size.height);//imageView.frame.size.width*9.6, imageView.frame.size.height*0.9
//scrollView.contentOffset = CGPointMake(imageView.frame.size.width/4,
// imageView.frame.size.height/4);
//CGRect rect = CGRectMake(119, 42, 208, 166);
scrollView.maximumZoomScale = 4.0;
scrollView.minimumZoomScale = 0.33;
scrollView.clipsToBounds = YES;
scrollView.delegate = self;
scrollView.bouncesZoom=FALSE;
[scrollView addSubview:imageView];
float minimumScale = [scrollView frame].size.width / [imageView frame].size.width;
[scrollView setMinimumZoomScale:minimumScale];
[scrollView setZoomScale:minimumScale];
}
imageView= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"KK_Map-02.jpg"]];
//self.imageView = imageView;
//[tempImageView release];
[super viewDidLoad];
//aWw.delegate = self;
//[scrollView setUserInteractionEnabled:YES];
scrollView.contentSize = CGSizeMake(imageView.frame.size.width, imageView.frame.size.height);//imageView.frame.size.width*9.6, imageView.frame.size.height*0.9
//scrollView.contentOffset = CGPointMake(imageView.frame.size.width/4,
// imageView.frame.size.height/4);
//CGRect rect = CGRectMake(119, 42, 208, 166);
scrollView.maximumZoomScale = 4.0;
scrollView.minimumZoomScale = 0.33;
scrollView.clipsToBounds = YES;
scrollView.delegate = self;
scrollView.bouncesZoom=FALSE;
[scrollView addSubview:imageView];
float minimumScale = [scrollView frame].size.width / [imageView frame].size.width;
[scrollView setMinimumZoomScale:minimumScale];
[scrollView setZoomScale:minimumScale];
}
Monday, March 14, 2011
JS to Obj-c and Objc to JS
search for text which you can to test against
- (BOOL)webView:(UIWebView *)localwebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSString *path = [[request URL] path];
NSString *pathTrimmed = [path lastPathComponent];
NSLog(@"sfdf %@",url);
NSLog(@"path f %@",pathTrimmed);
if ([pathTrimmed isEqualToString:@"Reset"]) {
// Display alert
UIAlertView *alertb = [[UIAlertView alloc] initWithTitle:@"You want to Reset Data??" message:@"" delegate:self cancelButtonTitle:@"No" otherButtonTitles: @"YES",nil];
alertb.tag=3;
[alertb show];
[alertb release];
return NO;
}
return YES;
}
and then based on alert call JS Function defined in html page
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 1) {
//NSLog(@" its done now uplaod data");
[localwebView stringByEvaluatingJavaScriptFromString:@"confirmation()"];
}
}
- (BOOL)webView:(UIWebView *)localwebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSString *path = [[request URL] path];
NSString *pathTrimmed = [path lastPathComponent];
NSLog(@"sfdf %@",url);
NSLog(@"path f %@",pathTrimmed);
if ([pathTrimmed isEqualToString:@"Reset"]) {
// Display alert
UIAlertView *alertb = [[UIAlertView alloc] initWithTitle:@"You want to Reset Data??" message:@"" delegate:self cancelButtonTitle:@"No" otherButtonTitles: @"YES",nil];
alertb.tag=3;
[alertb show];
[alertb release];
return NO;
}
return YES;
}
and then based on alert call JS Function defined in html page
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 1) {
//NSLog(@" its done now uplaod data");
[localwebView stringByEvaluatingJavaScriptFromString:@"confirmation()"];
}
}
Thursday, March 10, 2011
check inernet conection on iphone
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
//NSLog(@" SRRINF IS %@",connected);
wait(20);
if (connected == NULL) {
NSLog(@"Not connected");
UIAlertView *alertb = [[UIAlertView alloc] initWithTitle:@"Internet is down " message:@"Check your internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil,nil];
[alertb show];
[alertb release];
} else {
NSLog(@"Connected - %@",connected);
//NSLog(@" SRRINF IS %@",connected);
wait(20);
if (connected == NULL) {
NSLog(@"Not connected");
UIAlertView *alertb = [[UIAlertView alloc] initWithTitle:@"Internet is down " message:@"Check your internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil,nil];
[alertb show];
[alertb release];
} else {
NSLog(@"Connected - %@",connected);
Tuesday, March 8, 2011
ipad run
inseret this ti info.plost
NSMainNibFile~ipad
http:// www . devx.com/wireless/Article/44472/1763/page/2
NSMainNibFile~ipad
http:// www . devx.com/wireless/Article/44472/1763/page/2
Wednesday, February 16, 2011
DEALING WITH NULL SQL DATABASE
#pragma mark DEALING WITH NULL SQL DATABASE
char *currencyChars = (char *)sqlite3_column_text(compiledStatement, 3);
if (currencyChars !=NULL)
aFAQ.img = [NSString stringWithUTF8String: currencyChars];
char *currencyChars = (char *)sqlite3_column_text(compiledStatement, 3);
if (currencyChars !=NULL)
aFAQ.img = [NSString stringWithUTF8String: currencyChars];
Dynamic display of button from sql
for (NSString *arrayString in appDelegate.saveTCellImg )
{
k++;
CGRect frame = CGRectMake(curXLoc, curYLoc, 60, 50);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
UIImage *theImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[ NSURL URLWithString:arrayString]]];
NSLog(@" BUTTON INDEX IS = %d",k);
button.tag=k;//[arrayString intValue];
rowID=k;
[button setImage:theImage forState:UIControlStateNormal];
//[button setImage:[UIImage imageNamed:[appDelegate.saveTCellImg objectAtIndex:0]] forState:UIControlStateNormal];
[button setTitle:(NSString *)[appDelegate.a1 objectAtIndex:k] forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:@selector(buttonEvent: ) forControlEvents:UIControlEventTouchUpInside];
curXLoc +=60;// (kScrollObjWidth1);
if(curXLoc>=200)
{
curXLoc=20;
curYLoc+=150;
}
NSLog(@" WIDTH IS %d",curXLoc);
// NSLog(@" WIDTH IS %d",kScrollObjWidth1);
[self.view addSubview:button];
}
{
k++;
CGRect frame = CGRectMake(curXLoc, curYLoc, 60, 50);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
UIImage *theImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[ NSURL URLWithString:arrayString]]];
NSLog(@" BUTTON INDEX IS = %d",k);
button.tag=k;//[arrayString intValue];
rowID=k;
[button setImage:theImage forState:UIControlStateNormal];
//[button setImage:[UIImage imageNamed:[appDelegate.saveTCellImg objectAtIndex:0]] forState:UIControlStateNormal];
[button setTitle:(NSString *)[appDelegate.a1 objectAtIndex:k] forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:@selector(buttonEvent: ) forControlEvents:UIControlEventTouchUpInside];
curXLoc +=60;// (kScrollObjWidth1);
if(curXLoc>=200)
{
curXLoc=20;
curYLoc+=150;
}
NSLog(@" WIDTH IS %d",curXLoc);
// NSLog(@" WIDTH IS %d",kScrollObjWidth1);
[self.view addSubview:button];
}
Thursday, January 27, 2011
Sunday, January 23, 2011
add button to UItableview cell
myButton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton1.frame = CGRectMake(0, 20, 80, 30); // position in the parent view and set the size of the button
[myButton1 setTitle:@"MAIL!" forState:UIControlStateNormal];
// add targets and actions
[myButton1 addTarget:self action:@selector(buttonClicked1:) forControlEvents:UIControlEventTouchUpInside];
// add to a view
//[self addSubview:myButton];
myButton1.tag=jk;//indexPath.row;
//[self.view addSubview:myButton];
[cell.contentView addSubview:myButton1];
/// ADDING METHOD TO THOS BUTTONS
- (IBAction)buttonWasPressed:(id)sender
{
NSIndexPath *indexPath =
[self.myTableView
indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
NSUInteger row = indexPath.row;
// Do something with row index
}
myButton1.frame = CGRectMake(0, 20, 80, 30); // position in the parent view and set the size of the button
[myButton1 setTitle:@"MAIL!" forState:UIControlStateNormal];
// add targets and actions
[myButton1 addTarget:self action:@selector(buttonClicked1:) forControlEvents:UIControlEventTouchUpInside];
// add to a view
//[self addSubview:myButton];
myButton1.tag=jk;//indexPath.row;
//[self.view addSubview:myButton];
[cell.contentView addSubview:myButton1];
/// ADDING METHOD TO THOS BUTTONS
- (IBAction)buttonWasPressed:(id)sender
{
NSIndexPath *indexPath =
[self.myTableView
indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
NSUInteger row = indexPath.row;
// Do something with row index
}
Tuesday, January 18, 2011
color UI title sectionview
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// create the parent view that will hold header Label
UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 150.0, 44.0)]autorelease];
NSString *sectionName = nil;
switch(section)
{
case 0:
if(counter<=3)
NSLog(@"ok");
// create the buNSLog(@"ok");tton object
UILabel * headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero]autorelease] ;
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
headerLabel.textColor = [UIColor whiteColor];
headerLabel.highlightedTextColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:20];
headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 44.0);
// If you want to align the header text as centered
// headerLabel.frame = CGRectMake(150.0, 0.0, 300.0, 44.0);
headerLabel.text = @"Description"; // i.e. array element
[customView addSubview:headerLabel];
if(counter==7)
headerLabel.text = @""; // i.e. array element
[customView addSubview:headerLabel];
//sectionName = @"DES-";
break;
case 1:
{
return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// create the parent view that will hold header Label
UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 150.0, 44.0)]autorelease];
NSString *sectionName = nil;
switch(section)
{
case 0:
if(counter<=3)
NSLog(@"ok");
// create the buNSLog(@"ok");tton object
UILabel * headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero]autorelease] ;
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
headerLabel.textColor = [UIColor whiteColor];
headerLabel.highlightedTextColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:20];
headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 44.0);
// If you want to align the header text as centered
// headerLabel.frame = CGRectMake(150.0, 0.0, 300.0, 44.0);
headerLabel.text = @"Description"; // i.e. array element
[customView addSubview:headerLabel];
if(counter==7)
headerLabel.text = @""; // i.e. array element
[customView addSubview:headerLabel];
//sectionName = @"DES-";
break;
case 1:
Sunday, January 16, 2011
Avoid shuffling of data in UITABLE Section view
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier=nil ;
NSMutableArray *Array= [[[NSMutableArray alloc] initWithObjects: @"One",@"Two", @"Three",@"Ad",@"Ae",@"Ah",@"Aj" ,nil]autorelease];
CellIdentifier = [Array objectAtIndex:indexPath.section];
///302-1021-9244-4658-1994-3384
UITableViewCell * cell = [tabelView dequeueReusableCellWithIdentifier:CellIdentifier];
//number++;
// NSLog(@" NUMBER IS %d",number);
// if (cell != nil)
//if(number==1);
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
// // Set up the cell
appDelegate = (DatabaseTestAppDelegate *)[[UIApplication sharedApplication] delegate];
switch(indexPath.section)
{
}
}
NSString *CellIdentifier=nil ;
NSMutableArray *Array= [[[NSMutableArray alloc] initWithObjects: @"One",@"Two", @"Three",@"Ad",@"Ae",@"Ah",@"Aj" ,nil]autorelease];
CellIdentifier = [Array objectAtIndex:indexPath.section];
///302-1021-9244-4658-1994-3384
UITableViewCell * cell = [tabelView dequeueReusableCellWithIdentifier:CellIdentifier];
//number++;
// NSLog(@" NUMBER IS %d",number);
// if (cell != nil)
//if(number==1);
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
// // Set up the cell
appDelegate = (DatabaseTestAppDelegate *)[[UIApplication sharedApplication] delegate];
switch(indexPath.section)
{
}
}
Thursday, January 6, 2011
Load webview inside Table view
CGRect bounds = CGRectMake(10, 90, 320, 180);//[[UIScreen mainScreen] applicationFrame];
UIWebView *localwebView = [[UIWebView alloc] initWithFrame: bounds ];
[self.view addSubview:localwebView];
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
localwebView.scalesPageToFit = YES;
[localwebView loadRequest:request];
UIWebView *localwebView = [[UIWebView alloc] initWithFrame: bounds ];
[self.view addSubview:localwebView];
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
localwebView.scalesPageToFit = YES;
[localwebView loadRequest:request];
Subscribe to:
Posts (Atom)