Articles Tagged 'Objective-C'


Very short snippet: Objective-C, Selector from NSString

Objective-C is a wonderful language that allows you to do amazing things. One of the most interesting aspects is its dynamic invocation of methods (messages). It is possible, in fact, to obtain the address of a message from a string.

More ...

Very short snippet: UIWebView, and display PDF files inside

The object UIWebView can be used for the display of numerous files. For example you can use it to display - as well as QuickTime movies or YouTube - PDF or HTML files into our own code.

More ...

Very short snippet: composing emails to an iPhone, iPod or iPad

To compose an email in iPhone / iPod just add the framework MessageUI . In our controller to enter the inclusion of the framework and implement the protocol MFMailComposeViewControllerDelegate :

More ...

Objective-C class methods and self alloc

davanti al prototipo, tipo: When we define and use methods (messages) under Objective-C, we are often faced with the curious syntax that shows a sign - or + in front of the prototype, type:

1
2
3
4
5
6
7
/ / In the definition
void ) mioMessaggio; - (Void) mioMessaggio;

/ / Similarly, in the implementation
void ) mioMessaggio { - (Void) {mioMessaggio
/ / ...
}

Or:

1
2
3
4
5
6
7
/ / In the definition
void ) mioMessaggio; + (Void) mioMessaggio;

/ / Similarly, in the implementation
void ) mioMessaggio { + (Void) {mioMessaggio
/ / ...
}

The difference resides in the fact that the methods defined by the symbol - are methods for instance, and then linked to an object. The methods defined by the symbol + are called class methods, as they can be performed without allocating and instantiate the object in question.

sono due classi, molto usate, che contengono svariati metodi di classe. NSString or UIView are two classes, widely used, which contain several class methods. Class methods are used constantly, like when we initialize or allocate any object:

1
[ UIView alloc ] ; MyView UIView * = [UIView alloc];

The method alloc is a classic example, present in all objects and, as evidenced by the code, is a class method as claimed before allocation of the object itself.

Class methods can be useful in many cases, particularly when we create our object and we want to allocate and initialize it in fewer lines of code possible. Imagine having to collect an array in a set of objects defined by us. We define our first object, writing the code in the simplest way, without using class methods:

1
2
3
4
5
6
7
8
9
10
/ / DEFINITION the interface in myObject.h
# Import <Foundation/Foundation.h>

NSObject { @ Interface myObject: NSObject {
name; NSString * name;
lastname; NSString * lastname;
}

nonatomic, retain ) NSString * name; @ Property (nonatomic, retain) NSString * name;
nonatomic, retain ) NSString * lastname; @ Property (nonatomic, retain) NSString * lastname;

The implementation, in the simplest case, it may be nothing or:

1
2
3
4
5
6
7
8
9
10
11
12
/ / MyObject.m

# Import "myObject.h"
@ Implementation myObject

@ Synthesize name, lastname;

void ) dealloc { - (Void) dealloc {
; [Name release];
; [Lastname release];
; [Super dealloc];
}

When are we going to use our object, we would use code like this:

1
2
3
[ myObject alloc ] ; myObject * obj = [myObject alloc];
"Mario" ; obj.name @ = "John";
"Rossi" ; obj.lastname @ = "Smith";

If we wanted to create many objects of this type, and place them in an NSArray , the situation becomes a little awkward:

1
2
3
4
5
6
7
8
9
10
11
12
[ myObject alloc ] ; objA * myObject = [myObject alloc];
"Mario" ; objA.name @ = "John";
"Rossi" ; objA.lastname @ = "Smith";

[ myObject alloc ] ; objB * myObject = [myObject alloc];
"Carlo" ; objB.name @ = "Charles";
"Bianchi" ; objB.lastname @ = "Smith";

elenco = [ NSArray arrayWithObjects : objA, objB, nil ] ; NSArray * list = [ NSArray arrayWithObjects: objA, objB, nil];

; [ObjA release];
; [ObjB release];

per aggiungere man mano gli oggetti nel nostro elenco. It could improve the code by creating a loop for or using an NSMutableArray to add as objects in our directory. . However, the situation migliorebbe slightly, occasionally remain outside the property settings name and lastname . Would then be spontaneous, to start, add a method - object - initWithName that allow you to jump to any property settings, semplificandoci things a bit. In the implementation file myObject.m add:

1
2
3
4
5
6
7
id ) initWithName : ( NSString * ) stringName lastname : ( NSString * ) stringLastname { - (Id) initWithName: ( NSString *) StringName lastname: ( NSString *) {stringLastname
self = [ super init ] ) { if (self = [super init]) {
self.name = StringName;
self.lastname = stringLastname;
}
return self;
}

In doing so we have improved the situation, they can now write:

1
2
3
4
5
6
7
[ [ myObject alloc ] initWithName : @ "Mario" lastname : @ "Rossi" ] ; objA * myObject = [[myObject alloc] initWithName: @ "Mario" lastname: @ "Smith"];
[ [ myObject alloc ] initWithName : @ "Carlo" lastname : @ "Bianchi" ] ; objB * myObject = [[myObject alloc] initWithName: @ "Charles" lastname: @ "Smith"];

elenco = [ NSArray arrayWithObjects : objA, objB, nil ] ; NSArray * list = [ NSArray arrayWithObjects: objA, objB, nil];

; [ObjA release];
; [ObjB release];

, necessari per l'inserimento nell'array e liberare la memoria. Abbiammo yet still pointers objA and objB , necessary for the entry in the array and free memory. Wishing we could directly enter the creation of an object in populating the array, using autorelease to free memory, but the code still would not idle. Let me demonstrate how to resolve the issue with a class method. First of all we replace our - (id)initWidthName with:

1
2
3
4
5
6
7
8
9
10
id ) initWithName : ( NSString * ) name lastname : ( NSString * ) lastname { + (Id) initWithName: ( NSString *) name lastname: ( NSString *) {lastname
myObject * item;

item = [ [ self alloc ] init ] ) { if (item = [[self alloc] init]) {
/ / Init
item.name = name;
item.lastname = lastname;
}
item autorelease ] ; return [item autorelease];
}

In doing so we created a class method that allocates (in autorelase) and iniziallizza our subject, before you have the pointer to the instance. The code used is then:

1
2
3
4
elenco = [ NSArray arrayWithObjects : NSArray * list = [ NSArray arrayWithObjects:
@ "Mario" lastname : @ "Rossi" ] , [MyObject initWithName: @ "Mario" lastname: @ "Smith"],
@ "Carlo" lastname : @ "Bianchi" ] , [MyObject initWithName: @ "Charles" lastname: @ "Smith"],
; nil];

Much, much better ...

More ...

WordPress Plugin Maker

I'm really happy to be able to present a preview of the WordPress Plugin Maker, an application for Mac OS X (Snow Leopard) that allows you to create a skeleton of a WordPress Plugin in seconds, allowing you to set many parameters. The application is still under development, however, performs its task base and is easily usable and functional. Some features have not yet been included and the other is awaiting feedback from the "few" lucky beta testers.

More ...

How to get Latitude and Longitude in Objective-C

The MapKit framework provides many useful features, except the return of Latitude and Longitude from an address. In JavaScript, for example, you can use the service provided by Google Geocoding and discussed in Google Maps: How to get Latitude and Longitude from an address . On Apple iPhone or iPad, however, you can overcome the obstacle by using a different Google services. Specifically, you can directly call the url:

1
http://maps.google.com/maps/geo?q = [address] & output = csv

Where is [indirizzo] to enter the string with the address you want to transform coordinates. The output returned is of type:

1
200,8,41.9128300,12.2241172

). The first value, 200 , indicates that everything went well ( 200 OK ). The second, 8 , is the Google accuracy parameter (1-10). The last two values ​​are, finally, latitude and longitude. Now we see a prototype of a method can be included in our applications:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
CLLocationCoordinate2D ) getLocationFromAddress : ( NSString * ) address { - (CLLocationCoordinate2D) getLocationFromAddress: ( NSString *) address {
urlString = [ NSString stringWithFormat : @ "http://maps.google.com/maps/geo?q=%@&output=csv" , NSString * urlString = [ NSString stringWithFormat: @ "% @ http://maps.google.com/maps/geo?q = & output = csv"
NSUTF8StringEncoding ] ] ; [Address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

listItems = [ locationString componentsSeparatedByString : @ "," ] ; NSArray * ListItems = [locationString componentsSeparatedByString: @ ""];

/ / Int zoom = 0;
0.0 ; double latitude = 0.0;
0.0 ; double longitude = 0.0;

listItems count ] > = 4 && [ [ listItems objectAtIndex : 0 ] isEqualToString : @ "200" ] ) { if ([ListItems count]> = 4 && [[ListItems objectAtIndex: 0] isEqualToString: @ "200"]) {
/ / Zoom = [[ListItems objectAtIndex: 1] intValue];
listItems objectAtIndex : 2 ] doubleValue ] ; latitude = [[ListItems objectAtIndex: 2] doubleValue];
listItems objectAtIndex : 3 ] doubleValue ] ; longitude = [[ListItems objectAtIndex: 3] doubleValue];
{ Else {}
/ / Error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;

return location;
}

Notes of Interest

, alla stregua della funzione explode ( ) del PHP per intenderci. The string returned in locationString is "splitted" by the method componentsSeparatedByString , like the function explode ( ) of PHP for instance. In the example I proposed I entered - but commented - the code to retrieve even the Google parameter accuracy, precision or scale factor, denoted by zoom .

Source as

For completeness, I made ​​a small example application with which you can try the method proposed above, enter any address and the iPhone will display on the map.


Download Source

I thank the team devAPP for the inspiration of this article.

More ...

setAnimationDidStopSelector: different uses and advanced

In most cases, or because we are used or because we've seen in tutorials and in some texts, we use the setAnimationDidStopSelector in this manner:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
nil context : NULL ] ; [UIView beginAnimations: nil context: NULL];
1.5 ] ; [UIView setAnimationDuration: 1.5];
UIViewAnimationCurveEaseInOut ] ; [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
self ] ; [UIView setAnimationDelegate: self];
@selector ( removeView ) ] ; [UIView setAnimationDidStopSelector: @ selector (removeView)];

; myView.alpha = 0;

; [UIView commitAnimations];

/ /

void ) removeView { - (Void) {removeView
; [MyView removeFromSuperview];
}

come delegato e tramite la setAnimationDidStopSelector gli invia un messaggio removeView quando l'animazione è terminata. In the code above the setAnimationDelegate set self as delegate and through setAnimationDidStopSelector sends a message removeView when the animation is finished. The code itself is correct, however, makes use of a message definition ( removeView ) which could be omitted. Now, here is the same code, with the same effect, without the message removeView :

1
2
3
4
5
6
7
8
9
nil context : NULL ] ; [UIView beginAnimations: nil context: NULL];
1.5 ] ; [UIView setAnimationDuration: 1.5];
UIViewAnimationCurveEaseInOut ] ; [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
myView ] ; [UIView setAnimationDelegate: myView];
@selector ( removeFromSuperview ) ] ; [UIView setAnimationDidStopSelector: @ selector (removeFromSuperview)];

; myView.alpha = 0;

; [UIView commitAnimations];

! The interesting thing about this approach is that myView could be a subclass of UIView ! It may therefore be a custom class with our own messages and, in the manner set out, quietly called by setAnimationDidStopSelector . Moreover, the setAnimationDidStopSelector selectors agree with parameters:

1
2
3
4
5
6
7
8
9
nil context : NULL ] ; [UIView beginAnimations: nil context: NULL];
1.5 ] ; [UIView setAnimationDuration: 1.5];
UIViewAnimationCurveEaseInOut ] ; [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
myView ] ; [UIView setAnimationDelegate: myView];
@selector ( myMessage : param1 : ) ] ; [UIView setAnimationDidStopSelector: @ selector (myMessage: param1:)];

; myView.alpha = 0;

; [UIView commitAnimations];

This example can be extended to all cases here where we set a delegate, atro is not a pointer to an instance of any object.

More ...

How to locate images and views in Interface Builder

After explaining how to locate our strings in Xcode , as we see now is simple - applying the same technique - to locate and view images / interfaces created with Interface Builder.

Locate graphic resources

The process, as mentioned, is the same, if we have an image already included in our resources, or they insert a new one, and we want to "locate" - that is, managing two or more images based on the languages ​​supported - just click the button Right image ( Adium.png in this example) and select Get Info:

We click Make File Localizable in the lower left.

Click on Add and insert Localization Italian :

In order to obtain:

esattamente come accadeva con il testo: Our image is moved (physically, one of the rare times when that happens nell'alberatura Xcode is reflected on the filesystem) under virtual folders English.lproj and Italian.lproj exactly as happened with the text:

contiene una stessa versione dell'immagine. At this point each of the folders English.lproj and Italian.lproj contains the same version of the image. This image is manipulated within Interface Builder, where we will see - by default - the English version.
At this point, just overwrite one (or both files Adium.png ) to obtain a localization of the images "flash".

Locate the files XIB

Even the interfaces built with Interface Builder can be localized in their entirety, when it is deemed necessary. ) con interfaccia XIB , lo selezioniamo, scegliamo Get Info dal menu contestuale, rendiamo il file localizzabile, aggiungiamo la localizzazione in italiano: The procedure is identical to that performed with the graphical capabilities: add a ViewController (eg infoViewController ) XIB interface, we select it, choose Get Info from the contextual menu, give the file localizable, add localization in Italian:

ViewController

Click on English or Italian will open Interface Builder! ) all'interno della classica cartella Classes . This time, the filesystem, we will notice that you have created two directories ( English.lproj and Italian.lproj ) within the classical Classes folder. Both will have their files infoViewController.xib . The comfort in this, clearly resolved in the code, when we go to instantiate our controller code we will have a "clean" like this:

1
2
[ InfoViewController alloc ] ; InfoViewController * info = [InfoViewController alloc];
info.view ] ; [Self.view addSubview: info.view];

As you can see there is no trace of any statement concerning the location, totally managed by the system. The two interfaces, of course, can be completely different in that they are in all respects as two separate files XIB.

More ...

How to create your own protocol with delegated

Even in the most simple tutorial you can find the use of protocols. It will certainly happen to many of your view controller used in a protocol, inputting, next to the definition of the interface, a statement similar to:

1
2
3
UIViewController <uiwebviewdelegate> { @ Interface myViewController: UIViewController {<uiwebviewdelegate>
...
}

More ...

Very short snippet: get the output of a URL in Objective-C

Perhaps I should write "Very very very, short snippets", however, is an excellent and convenient "trick" that I am going to show. Executing the "two" lines of code shown below, you can get the output of any URL and manipulate it.

More ...



Stop SOPA