Archive for the ‘Objective C’ Category

27
Apr
NSMutableAttributedString *myAttrStr = [[NSMutableAttributedString alloc] initWithString:@"my test string"]; // Creating a NSAttributedString object

CGColorRef myRedColor = [UIColor redColor].CGColor; // Creating a CGColorRef to set the value to

NSDictionary *newAttribute = [NSDictionary dictionaryWithObject:(id) myRedColor forKey:(id)kCTForegroundColorAttributeName]; // Setting the foreground attribute value the color reference created.

[myAttrStr addAttributes:newAttribute range:NSMakeRange(0, [myAttrStr length])]; // Setting the attribute dictionary to the NSAttributedString object

, ,

26
Apr

You can have a structure like this each value of plist should contain a dictionary. Like in you example entertainment will be a dictionary by default you can add a bool flag to the dictionary. Something like this

NSDictionary *entertainmentDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Entertainment",@"name",[NSNUmber numberWithBool:YES],@"Checked",nil];

Then when displaying in table you can get the value of bool flag from dictionary like this

NSDictionary *entD = [arrayOfPlistItems objectAtIndex:indexPath.row];

BOOL checked = [[entD objectForKey:@"Checked"] boolValue];

//Not replace this with actual code it is for explaining purpose only

if(checked) {

cell.accessoryType = checkmarktype;

 

}else {

cell.accessoryType = none;

}

,

18
Apr

Consider a UIButton object, myButtonObject, for which you want to give the zoom in and out animation. Now use the following code to give the desired animation to the button.

[UIView beginAnimations:nil context:myButtonObject]; // Giving the context of the animation to the button you want to animate.

[UIView setAnimationDuration:1]; // Duration of each animation in seconds

[UIView setAnimationRepeatCount:5]; // Number of times you want the animation to perform

[UIView setAnimationRepeatAutoreverses:YES]; // YES means will go back to the original state after completion of each animation loop

CGRect rect = myButtonObject.bounds; // Getting the current bounds of the button

rect.size.width += 15; // Increasing the width of the button by 15 points

rect.size.height += 15; // Increasing the height of the button by 15 points

myButtonObject.bounds = rect; // Assigning the modified width and height to the button.

[UIView commitAnimations]; // Committing the animation. Now the animation will start.

, , , ,

18
Apr

For command line installation of cocos3D, follow the following steps :

1. Set the path of the command line to the cocos3d folder.

2. Now execute the following command to install cocos3D. Please not that we are installing cocos3D as an extension of cocos2D. So you have to give like this.

./install-cocos3d.sh -u -f -2 yourcocos2dinstalledlocation

Now you are ready to go with cocos3D. If the Xcode was open when you were installing cocos3D, then restart Xcode for the changes to take effect.

, , ,

12
Apr

Automatic Reference Counting (ARC) for Objective-C makes memory management the job of the compiler. By enabling ARC with the new Apple LLVM compiler, you will never need to type retain or release again, dramatically simplifying the development process, while reducing crashes and memory leaks. The compiler has a complete understanding of your objects, and releases each object the instant it is no longer used, so apps run as fast as ever, with predictable, smooth performance.

12
Apr

One of the neat features available in iPhone OS 3.0 is the GameKit framework. The GameKit framework contains APIs to allow communications over a Bluetooth network. Using these APIs, you can create peer-to-peer games and applications with ease. Unlike other mobile platforms, using Bluetooth as a communication channel in iPhone is way easier than expected. Hence, in this article, I will show you how to build a simple application that allows two iPhone or iPod Touch devices to communicate with each other.

Regards: http://www.devx.com/

Creating the Project

Using Xcode, create a new View-based Application project and name it as Bluetooth.

All the various APIs for accessing the Bluetooth is located in the GameKit framework. Hence, you need to add this framework to your project. Add a new Framework to the project by right-clicking on the Frameworks group in Xcode and selecting Add, Existing Frameworks. Select GameKit.framework

In the BluetoothViewController.h file, declare the following object, outlets, and actions:

#import

#import

@interface BluetoothViewController : UIViewController {

GKSession *currentSession;

IBOutlet UITextField *txtMessage;

IBOutlet UIButton *connect;

IBOutlet UIButton *disconnect;

}

@property (nonatomic, retain) GKSession *currentSession;

@property (nonatomic, retain) UITextField *txtMessage;

@property (nonatomic, retain) UIButton *connect;

@property (nonatomic, retain) UIButton *disconnect;

-(IBAction) btnSend:(id) sender;

-(IBAction) btnConnect:(id) sender;

-(IBAction) btnDisconnect:(id) sender;

@end

The GKSession object is used to represent a session between two connected Bluetooth devices. You will make use of it to send and receive data between the two devices.

In the BluetoothViewController.m file, add in the following statements in bold:

 

#import "BluetoothViewController.h"

#import

@implementation BluetoothViewController

@synthesize currentSession;

@synthesize txtMessage;

@synthesize connect;

@synthesize disconnect;

Double-click on BluetoothViewController.xib to edit it in Interface Builder. Add the following views to the View window :

  • Text Field
  • Round Rect Button

 

Perform the following actions:

  • Control-click on the File’s Owner item and drag and drop it over the Text Field view. Select txtMessage.
  • Control-click on the File’s Owner item and drag and drop it over the Connect button. Select connect.
  • Control-click on the File’s Owner item and drag and drop it over the Disconnect button. Select disconnect.
  • Control-click on the Send button and drag and drop it over the File’s Owner item. Select btnSend:.
  • Control-click on the Connect button and drag and drop it over the File’s Owner item. Select btnConnect:.
  • Control-click on the Disconnect button and drag and drop it over the File’s Owner item. Select btnDisconnect:.

Right-click on the File’s Owner item to verify that all the connections are made correctly

 

Back in Xcode, in the BluetoothViewController.m file, add in the following statements in bold:

 

- (void)viewDidLoad {

[connect setHidden:NO];

[disconnect setHidden:YES];

[super viewDidLoad];

}

- (void)dealloc {

[txtMessage release];

[currentSession release];

[super dealloc];

}

 

 

Searching for Peer Devices

 

Now that all the plumbings for the project have been done, you can now focus on the APIs for accessing other Bluetooth devices.

In the BluetoothViewController.h file, declare a GKPeerPickerController object:

 

#import "BluetoothViewController.h"

@implementation BluetoothViewController

@synthesize currentSession;

@synthesize txtMessage;

@synthesize connect;

@synthesize disconnect;

GKPeerPickerController *picker;

The GKPeerPickerController class provides a standard UI to let your application discover and connect to another Bluetooth device. This is the easiest way to connect to another Bluetooth device.

To discover and connect to another Bluetooth device, implement the btnConnect: method as follows:

 

-(IBAction) btnConnect:(id) sender {

picker = [[GKPeerPickerController alloc] init];

picker.delegate = self;

picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;

[connect setHidden:YES];

[disconnect setHidden:NO];

[picker show];

}

The connectionTypesMask property indicates the types of connections that the user can choose from. There are two types available: GKPeerPickerConnectionTypeNearby and GKPeerPickerConnectionTypeOnline. For Bluetooth communication, use the GKPeerPickerConnectionTypeNearby constant. The GKPeerPickerConnectionTypeOnline constant indicates an Internet-based connection.

When remote Bluetooth devices are detected and the user has selected and connected to one of them, the peerPickerController:didConnectPeer:toSession: method will be called. Hence, implement this method as follows:

- (void)peerPickerController:(GKPeerPickerController *)picker

didConnectPeer:(NSString *)peerID

toSession:(GKSession *) session {

self.currentSession = session;

session.delegate = self;

[session setDataReceiveHandler:self withContext:nil];

picker.delegate = nil;

[picker dismiss];

[picker autorelease];

}

When the user has connected to the peer Bluetooth device, you save the GKSession object to the currentSession property. This will allow you to use the GKSession object to communicate with the remote device.

If the user cancels the Bluetooth Picker, the peerPickerControllerDidCancel: method will be called. Define this method as follows:

- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker

{

picker.delegate = nil;

[picker autorelease];

[connect setHidden:NO];

[disconnect setHidden:YES];

}

To disconnect from a connected device, use the disconnectFromAllPeers method from the GKSession object. Define the btnDisconnect: method as follows:

-(IBAction) btnDisconnect:(id) sender {

[self.currentSession disconnectFromAllPeers];

[self.currentSession release];

currentSession = nil;

[connect setHidden:NO];

[disconnect setHidden:YES];

}

When a device is connected or disconnected, the session:peer:didChangeState: method will be called. Implement the method as follows:

- (void)session:(GKSession *)session

peer:(NSString *)peerID

didChangeState:(GKPeerConnectionState)state {

switch (state)

{

case GKPeerStateConnected:

NSLog(@"connected");

break;

case GKPeerStateDisconnected:

NSLog(@"disconnected");

[self.currentSession release];

currentSession = nil;

[connect setHidden:NO];

[disconnect setHidden:YES];

break;

}

}

Handling this event will allow you to know when a connection is established, or ended. For example, when the connection is established, you might want to immediately start sending data over to the other device.

Sending Data

To send data to the connected Bluetooth device, use the sendDataToAllPeers: method of the GKSession object. The data that you send is transmitted via an NSData object; hence you are free to define your own application protocol to send any types of data (e.g. binary data such as images). Define the mySendDataToPeers: method as follows:

- (void) mySendDataToPeers:(NSData *) data

{

if (currentSession)

[self.currentSession sendDataToAllPeers:data

withDataMode:GKSendDataReliable

error:nil];

}

Define the btnSend: method as follows so that the text entered by the user will be sent to the remote device:

-(IBAction) btnSend:(id) sender

{

//---convert an NSString object to NSData---

NSData* data;

NSString *str = [NSString stringWithString:txtMessage.text];

data = [str dataUsingEncoding: NSASCIIStringEncoding];

[self mySendDataToPeers:data];

}

 

Receiving Data

When data is received from the other device, the receiveData:fromPeer:inSession:context: method will be called. Implement this method as follows:

- (void) receiveData:(NSData *)data

fromPeer:(NSString *)peer

inSession:(GKSession *)session

context:(void *)context {

//---convert the NSData to NSString---

NSString* str;

str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data received"

message:str

delegate:self

cancelButtonTitle:@"OK"

otherButtonTitles:nil];

[alert show];

[alert release];

}

Here, the received data is in the NSData format. To display it using the UIAlertView class, you need to convert it to an NSString object.

 

Testing the Application

Once the application is deployed to the two devices, launch the application on both devices. On each device, tap the Connect button. The GKPeerPickerController will display the standard UI to discover other devices.

When another device tries to connect to you, you will see the popup. Tap on Accept to connect and Decline to decline the connection.

If you are connected, you can now enter some text and start sending to the other device. Data received from another device will be shown in an alert view.

, , ,

12
Apr

To convert an existing project from a non-ARC(Automatic Reference Counting) project to an ARC, you have to do the following :

  1. Go to the Edit menu of the Xcode.
  2. Select Refactor menu from the list of menus which appear.
  3. Now select Convert to Objective-C ARC option from the sub menus which appear.
  4. From the window which appears next, select your project target to convert to ARC.
  5. Click the Check button and Xcode will now ready your app to convert to ARC based project and it will instruct you about what are the modifications in the code that needed to be done to convert the app to ARC.

Once the all issues are solved, the wizard will show the modifications made also.

, , ,

12
Apr

We can identify whether a Xcode project is using Automatic Reference Counting(ARC) or not, by checking the Objective-C Automatic Reference Counting flag of the compiler.

To check this flag,

select Xcode project from the Project Navigator in the left panel, now on the right panel, select project and check the Objective-C Automatic Reference Counting flag. If this flag is set to Yes, then the project is using ARC and if it is set to No, then the project is not using ARC.

Note that ARC is only available from Xcode v 4.3

, , ,

06
Apr

CocosDenshion provides functionality to change the pitch, gain, and pan properties of an
audio source. Pitch is the frequency, gain is volume, and pan is a way to shift volume between
left and right speakers. In this example, we will create a music-bending instrument to display
these properties being dynamically modifed.

Execute the following code:

#import "SimpleAudioEngine .h"
@implementation Ch6_AudioProperties
-(CCLayer*) runRecipe {
//Enable accelerometer support
self.isAccelerometerEnabled = YES;
[[UIAccelerometer sharedAccelerometer]setUpdateInterval : (1.0/60)];
//Add background
CCSprite *bg = [CCSprite spriteWithFile :@"synth_tone_sheet.png"];
bg.position = ccp(240,160);
[self addChild:bg];
// Initialize the audio engine
sae = [SimpleAudioEngine sharedEngine ] ;
//Background music is stopped on resign and resumed on  becoming active
[[CDAudioManager sharedManager] setResignBehavior :kAMRBStopPlay autoHandle :YES] ;
// Initialize note container
notes = [[NSMutableDictionary alloc]init] ;
noteSprites = [[NSMutableDictionary alloc]init] ;
//Preload tone
[sae preloadEffect :@"synth_tone_mono.caf"];
return self ;
}
-(void)ccTouchesBegan:(NSSet*)toucheswithEvent:(UIEvent*)event {
//Process multiple touches
for(int i=0 ; i<[[ touches allObjects] count ] ; i++){
UITouch *touch = [[touches allObjects]objectAtIndex : i ] ;
CGPoint point = [touch locationInView:[touch view]] ;
point = [[CCDi rector sharedDirector ] convertToGL: point ] ;
//Use [ touch hash] as a key for this sound source

NSString *key = [NSString stringWithFormat :@"%d" , [ touch hash] ] ;
if( [notes objectForKey:key] ){
CDSoundSource *sound = [notes objectForKey:key] ;
[sound release ] ;
[notes removeObjectForKey:key] ;
CCSpr i te *spr i te = [noteSprites objectForKey:key] ;
[self removeChild: sprite cleanup :YES] ;
[noteSprites removeObjectForKey:key] ;
}
//Play our sound wi th cus tom pi tch and gain
CDSoundSource *sound = [ [sae soundSourceForFile :@"synth_tone_mono.caf" ] retain] ;
[sound play] ;
sound.looping = YES;
[notes setObject : soundforKey:key] ;
sound.pitch = point.x/240.0f ;
sound.gain = point.y/320.0f ;
//Show music note where you touched
CCSprite *sprite = [CCSprite spriteWithFile :@"music_note .png" ] ;
sprite.position = point ;

sprite.scale = (point.y/320.0f)/2 + 0.25f ;
}
}
}
-(void) ccTouchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
//Stop sounds and remove sprites
for( int i=0 ; i<[[ touches allObjects]count];i++){
UITouch *touch = [ [ touches allObjects ] objectAtIndex : i] ;
CGPoint point = [ touch locationInView: [ touch view]] ;
point = [[CCDirector sharedDirector ] convertToGL:point] ;
NSString *key = [NSString stringWithFormat :@"%d",[ touch hash]] ;
if( [notes objectForKey:key] ){
//Stop and remove sound source
CDSoundSource *sound = [notes objectForKey:key] ;
[sound stop] ;
[sound release ] ;
[notes removeObjectForKey:key] ;
//Remove sprite
CCSprite *sprite = [noteSprites objectForKey:key] ;
[self removeChild: sprite cleanup :YES] ;

The first thing needed for this recipe is a short, constant, mid-range synthesized tone. This
was created in GarageBand and then modifed using Audacity. When you touch the screen
the note is played:

CDSoundSource *sound = [ [sae soundSourceForFi le :@"synth_tone_mono.caf" ] retain] ;
[sound play] ;
sound.looping = YES;

Now we need to set the pitch between 0 and 2 according to the X position of the touch:

sound.pitch = point.x/240.0f ;

We set the gain property between 0 and 1 according to the Y position of the touch:

sound.gain = point.y/320.0f ;

Tilting the device will set the pan property. Tilt to the left to hear all tones more in your left ear
and to the right to hear them more in your right:

for( id s in notes){
CDSoundSource *sound = [notes objectForKey: s ] ;
sound.pan = -acceleration .y;  / /"Turn" left to pan to the left

Regards: http://my.safaribooksonline.com/

, , ,

06
Apr

 

 

//All game logic has been omitted from the following code.

 

Execute the following code:

#import "ActualPath .h"

@implementation Ch2_SavingDataPlist

- (CCLayer*) runRecipe {

[self loadHiScores ] ;

return self ;

}

- (void) loadHiScores {

/ /Our template and file names

NSString *templateName = @"whackamole_template.plist" ;

NSString *fileName = @"whackamole.plist" ;

/ /Our dictionary

NSMutableDictionary *fileDict ;

/ /We get our file path

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;

NSString *documentsDirectory = [paths objectAt Index :0] ;

NSString *filePath = [documentsDirectory stringByAppendingPathComponent :fileName ] ;

if( ! [ [NSFileManager defaultManager ] fileExistsAtPath:filePath] ){

/ / If file doesn't exist in document directory create a new one

from the template

fileDict = [NSMutableDictionary dictionaryWithContentsOfFile :getActualPath( templateName) ] ;

}

else{

/ / If it does we load it in the dict

fileDict = [NSMutableDictionary dictionaryWithContentsOfFile :filePath] ;

}

NSMutableDictionary *fileDict ;

/ /We get our file path

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;

NSString *documentsDirectory = [paths objectAtIndex :0] ;

NSString *filePath = [documentsDirectory stringByAppendingPathComponent :fileName ] ;

if( ! [ [NSFileManager defaultManager ] fileExistsAtPath:filePath] ){

/ / If file doesn' t exist in document directory create a new one

from the template

fileDict = [NSMutableDictionary dictionaryWithContentsOfFile :getActualPath( templateName) ] ;

}

else{

/ / If it does we load it in the dict

fileDict = [NSMutableDictionary dictionaryWithContentsOfFile :filePath] ;

}

/ /Load hiscores into our dictionary

hiScores = [fileDict objectForKey:@"hiscores" ] ;

[newScore setObject : [NSNumber numberWithInt :currentScore ] forKey:@"score" ] ;

[hiScores addObject :newScore ] ;

}

/ /Write dict to file

[fileDict writeToFile :filePath atomically:YES] ;

}

- (void) deleteHiScores {

/ /Our file name

NSString *fileName = @"whackamole.plist" ;

/ /We get our file path

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;

NSString *documentsDirectory = [paths objectAt Index :0] ;

NSString *filePath = [documentsDirectory stringByAppendingPathComponent :fileName ] ;

/ /Delete our file

[ [NSFileManager defaultManager ] removeItemAtPath:filePatherror :nil ] ;

 

Whichever file we load, the loading line looks like this:

fileDict = [NSMutableDictionary dictionaryWithContentsOfFile :filePath] ;

After modifying the fileDict dictionary we save it to whackamole.plist in the

Documents directory:

[fileDict writeToFile :filePath atomically:YES] ;

All things considered, this is a very simple way to persist data.

 

Regards:http://my.safaribooksonline.com/

, , ,