
Articles Tagged 'Apple'
How to set XCode to use the iPhone instead of the simulator
iPhone: Create a way to respond to events that cross class
Normally an event, which is nothing but a message is fixed (set and implemented) in the same class or context, the function or procedure "caller". o in un UIViewController . For example if we add a button UIButton via code (programmatically), we can find our class in a UIView or a UIViewController . In both cases the task allocation and initialization of the button will be followed by the setting of target that should receive a message when it "clicks" the button, type:
1 2 3 4 5 6 7 8 9 | [ UIButton buttonWithType : UIButtonTypeRoundedRect ] ; UIButton * button = [UIButton buttonWithType: UIButtonTypeRoundedRect]; 10 , 180 , 300 , 30 ) ; bottone.frame = CGRectMake (10, 180, 300, 30); @ "Press me" forState : UIControlStateNormal ] ; [Button setTitle: @ "Press me" Forst: UIControlStateNormal]; / / Decide who should receive the message UIControlEventTouchUpInside self action : @selector ( onButtonClicked ) forControlEvents : UIControlEventTouchUpInside ] ; [AddTarget button: self action: @ selector (onButtonClicked) forControlEvents: UIControlEventTouchUpInside]; / / ... void ) onButtonClicked { - (Void) {onButtonClicked / / ... } |
Line 5 decides who the code shown above (the object) and what (method) "call" when our button is pressed. In the example above is also known that the pressure setting of the message is sent to the method onButtonClick implemented below, then part of the same context (or class). potremmo inviare il nostro messaggio ad un qualsiasi altro oggetto, posto quindi al difuori del contesto in uso. The first consideration is obvious that we can do, then, is that by altering the parameters self and action we can send our message to any other object, then place in the context difuori in use. : Here's an example: a class UIApplicationDelegate create a UIViewController :
1 2 3 4 5 | / / / / MyAppDelegate.m / / SplashScreenController alloc ] ; splashScreenController = [SplashScreenController alloc]; splashScreenController.view ] ; [Window addSubview: splashScreenController.view]; |
associata al UIViewController stesso: The SplashScreenController exposes a method that allows you to animate the UIView associated with UIViewController same:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | / / / / SplashScreenController.m / / void ) animateBackgroundDown { - (Void) {animateBackgroundDown nil context : nil ] ; [UIView beginAnimations: nil context: nil]; 0.75 ] ; [UIView setAnimationDuration: 0.75]; UIViewAnimationCurveEaseInOut ] ; [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut]; self ] ; [UIView setAnimationDelegate: self]; @selector ( onAnimationFinished ) ] ; [UIView setAnimationDidStopSelector: @ selector (onAnimationFinished)]; CGRect ) { 0 , 480 , 320 , 480 } ; self.view.frame = (CGRect) {0, 480, 320, 480}; ; [UIView commitAnimations]; } / / ... void ) onAnimationFinished { - (Void) {onAnimationFinished "Animazione terminata" ) ; NSLog (@ "Animation is finished"); } |
. The above code shows a method defined inside the class SplashScreenController type UIViewController . ) onAnimationFinished definito più sotto, facente parte sempre della classe SplashScreenController . It does nothing but animate the UIView animating it down, and when the animation is complete, call (send a message to itself - hence self ) onAnimationFinished defined below, is part of the class always SplashScreenController . , non saremo informati della fine dell'animazione: It follows that in our myAppDelegate , when we invoke the method animateBackgroundDown , we will not be informed of the end of the animation:
1 2 3 4 | / / / / MyAppDelegate.m / / ; [SplashScreenController animateBackgroundDown]; |
What we might want, instead, is to create a new version of animateBackgroundDown that tell me where to send the message at the end of animation, and which method to call. In practice we want to make sure to write in our class myAppDelegate :
1 2 3 4 5 6 7 8 | / / / / MyAppDelegate.m / / self selector : @selector ( onAnimationFinished ) ] ; [SplashScreenController animateBackgroundDown: self selector: @ selector (onAnimationFinished)]; / / ... void ) onAnimationFinished { - (Void) {onAnimationFinished "Animazione terminata" ) ; NSLog (@ "Animation is finished"); } |
, bensì in myAppDelegate . This time the method onAnimationFinished is not in the UIViewController , but in myAppDelegate . nel modo seguente: To do this simply change the method animateBackgroundDown in UIViewController as follows:
1 2 3 4 5 6 7 8 9 10 11 12 | / / / / SplashScreenController.m / / void ) animateBackgroundDown : ( id ) target selector : ( SEL ) selector { - (Void) animateBackgroundDown: (id) target selector: (SEL) selector { nil context : nil ] ; [UIView beginAnimations: nil context: nil]; 0.75 ] ; [UIView setAnimationDuration: 0.75]; UIViewAnimationCurveEaseInOut ] ; [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut]; target ] ; [UIView setAnimationDelegate: target]; selector ] ; [UIView setAnimationDidStopSelector: selector]; CGRect ) { 0 , 480 , 320 , 480 } ; self.view.frame = (CGRect) {0, 480, 320, 480}; ; [UIView commitAnimations]; } |
). Now we have a method that takes the "context" ( target ) and the method to call ( selector ). a qualsiasi altro “oggetto” / classe in grado di riceverlo. Now, when the animation ends, the message AnimationDidStop will be sent to myAppDelegate any other "object" / class that can receive it.
Objective-C: an alternative to using CGRectMake
CGRectMake() is a function (actually an inline # define) used a lot especially when you create graphics objects from code or user interface. o UIImageView . CGRectMake() restituisce una struct (struttura di tipo) CGRect : Its use is therefore often associated initialization components of UIKit , but also to simple UIView or UIImageView . CGRectMake() returns a struct (structure type) CGRect :
1 2 3 4 5 | struct {CGRect CGPoint origin; CGSize size; }; typedef struct CGRect CGRect; |
: Which in turn is composed of two different struct CGPoint and CGSize :
1 2 3 4 5 6 7 8 9 10 11 12 13 | struct {CGPoint CGFloat x; CGFloat y; }; typedef struct CGPoint CGPoint; / * Sizes. * / struct {CGSize CGFloat width; CGFloat height; }; typedef struct CGSize CGSize; |
. That, in turn, again, contain types CGFloat or type float . If we analyze the code of CGRectMake () are:
1 2 3 4 5 6 7 8 | CG_INLINE CGRect CGRectMake (CGFloat x, y CGFloat, CGFloat width, height CGFloat) { CGRect rect; y; rect.origin.x = x, y = rect.origin.y; height; rect.size.width = width, height = rect.size.height; return rect; } |
It follows, therefore, that this piece of code:
1 2 3 4 | [ UIButton buttonWithType : UIButtonTypeRoundedRect ] ; UIButton gbutton * = [UIButton buttonWithType: UIButtonTypeRoundedRect]; 12 , 409 , 100 , 40 ) ; gbutton.frame = CGRectMake (12, 409, 100, 40); @ "Press" forState : UIControlStateNormal ] ; [Gbutton setTitle: @ "Press" Forst: UIControlStateNormal]; gbutton ] ; [MainWindow addSubview: gbutton]; |
It could rightly be written as:
1 2 3 4 | [ UIButton buttonWithType : UIButtonTypeRoundedRect ] ; UIButton gbutton * = [UIButton buttonWithType: UIButtonTypeRoundedRect]; CGRect ) { 12 , 409 , 100 , 40 } ; gbutton.frame = (CGRect) {12, 409, 100, 40}; @ "Press" forState : UIControlStateNormal ] ; [Gbutton setTitle: @ "Press" Forst: UIControlStateNormal]; gbutton ] ; [MainWindow addSubview: gbutton]; |
Just to speed things up 'the code is running ... ![]()
Xcode shortcut
Xcode is a really good development environment, nice and full of details that make writing efficient code and pleasant. Among these is the ease of auto-complete when typing, especially when writing applications for Apple iPhone, where the frameworks are many and remember syntax and nomenclature company by a few.
Xcode: Debugging tips on Preferences
Using the Xcode Preferences you can set the behavior of the atmosphere during the debugging phase of an iPhone application. The default settings, in fact, are very uncomfortable when you try and try again an application, for example, after launching our application, you must manually open the Console window to see the output of various NSLog() . Xcode also lets the previous sessions in order to force us to clean the window by hand. Fortunately, you can solve the problem by acting on the Preferences:

As shown above, simply select an item from the menu on start to decide which debug window to open automatically at startup of our valid if (I & Debugger Console set but you can choose those that best suits you). On the right, then we find Auto Clear Debug Console, so you always start with a clean console.
iPhone SecondApp: Guess the number - Part 2
As mentioned FirstApp iPhone: Guess the number - Part 1 we see how to make an application for the Apple iPhone without using Interface Builder! Indeed, we will eliminate physical files created by Interface Builder, Xcode wizard. At the end of this post, then, we have an application identical in all respects, to that achieved in the first part, with the difference that we will achieve all our visual components, including the main Window, completely to code.
The application already made, if you just want to download, is available on my Google Code repository:
I would like to point out immediately as the ZIP of this example weighing less than the last time! ![]()
We create the project
We start by creating our project SecondApp (to distinguish it from FirstApp), although this time choose Window-based Application:

Now let's delete everything related to Interface Builder. : eliminatelo anche dal file system, quindi selezionate Also Move to Trash . Delete the file MainWindow.xib , located in the folder Resources : also delete it from the file system, then select Also Move to Trash. nella casella Main nib file base name : Select then the file SecondoApp-info.plist and delete the reference to the MainWindow nib box Main base file name:

At this point we no longer have any Windows, at least through Interface Builder. , e modifichiamo la funzione main() in questo modo: So we open the file main.m , situated in Other Sources , and modify the function main() like this:
1 2 3 4 5 6 7 8 9 10 11 | int argc, char * argv [ ] ) { int main (int argc, char * argv []) { pool = [ [ NSAutoreleasePool alloc ] init ] ; NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc] init]; / / By removing the file. XIB we missed the point / / Delegate to the JPA, then pass it to "hand" UIApplicationMain ( argc, argv, nil , @ "SecondAppAppDelegate" ) ; int retVal = UIApplicationMain (argc, argv, nil, @ "SecondAppAppDelegate"); ; [Pool release]; return retVal; } |
Open SecondAppAppDelegate.me then create the main Window in code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | void ) applicationDidFinishLaunching : ( UIApplication * ) application { - (Void) applicationDidFinishLaunching: (UIApplication *) application { / / Get the screen size (320, 480) UIScreen mainScreen ] applicationFrame ] ; CGRect windowRect = [[UIScreen Mainscreen] applicationFrame]; / / Create a window - as we have done in Interface Builder bye bye [ [ UIWindow alloc ] initWithFrame : windowRect ] ; MainWindow UIWindow * = [[UIWindow alloc] initWithFrame: windowRect]; / / Set the background of the Window to yellow, to differentiate / / The previous application FirstApp [ UIColor yellowColor ] ] ; [MainWindow setBackgroundColor: [UIColor yellowColor]]; mainWindow ] ; [Self setWindow: mainWindow]; ; [Window makeKeyAndVisible]; ; [MainWindow release]; } |
You can already test the application, if you get a yellow window you did everything right!
, necessario solo se si usa Interface Builder. In the file SecondAppAppDelegate.h we can eliminate IBOutlet , only needed if you use Interface Builder. Also add here that our global variables, the last time we had entered in the Controller. Then modify the file SecondAppAppDelegate.h :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # Import <UIKit/UIKit.h> NSObject <UIApplicationDelegate> { @ Interface SecondAppAppDelegate: NSObject {<UIApplicationDelegate> UIWindow * window; UITextField * number; UIButton * button; numeroACaso int; } nonatomic, retain ) UIWindow * window; @ Property (nonatomic, retain) UIWindow * window; void ) controllaNumero; - (Void) getNumber; @ End |
, in quanto non stiamo usando Interface Builder. Again we have prepared the method definition controllaNumero , like last time, but we have eliminated the indication IBAction , because you are not using Interface Builder.
We build the interface from code
It 'time to create code using all components of our interface. ed inseriamo il seguente codice: Let's go back to the file SecondAppAppDelegate.m , posizioniamoci before [mainWindow release] and insert the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | / / Create the title bar [ [ UINavigationBar alloc ] initWithFrame : CGRectMake ( 0.0 , 0.0 , 320.0 , 44.0 ) ] ; UINavigationBar myNavigationBar * = [[UINavigationBar alloc] initWithFrame: CGRectMake (0.0, 0.0, 320.0, 44.0)]; myNavigationBar.barStyle = UIBarStyleDefault; [ [ UINavigationItem alloc ] initWithTitle : @ "Indovina un numero" ] ; UINavigationItem navigationItem * = [[UINavigationItem alloc] initWithTitle: @ "Guess a number"]; navigationItem animated : NO ] ; [MyNavigationBar pushNavigationItem: navigationItem animated: NO]; myNavigationBar ] ; [Window addSubview: myNavigationBar]; / / Create the label [ [ UILabel alloc ] initWithFrame : CGRectMake ( 10 , 50 , 300 , 80 ) ] ; UILabel myLabel * = [[UILabel alloc] initWithFrame: CGRectMake (10, 50, 300, 80)]; UIColor clearColor ] ; myLabel.backgroundColor = [UIColor clearColor]; ; myLabel.numberOfLines = 2; "iPhone ha pensato un numero da 1 a 10, prova ad indovinarlo?" ; myLabel.text = @ "iPhone has designed a number from 1 to 10, try to guess?" myLabel ] ; [Window addSubview: myLabel]; / / Create text input UITextField alloc ] initWithFrame : CGRectMake ( 10 , 120 , 300 , 30 ) ] ; number = [[UITextField alloc] initWithFrame: CGRectMake (10, 120, 300, 30)]; numero.borderStyle = UITextBorderStyleRoundedRect; numero.textAlignment = UITextAlignmentCenter; numero.keyboardType = UIKeyboardTypeNumberPad; "Inserisci il numero" ; numero.placeholder = @ "Enter the number"; numero ] ; [Window addSubview: number]; / / Create the button UIButton buttonWithType : UIButtonTypeRoundedRect ] ; button = [UIButton buttonWithType: UIButtonTypeRoundedRect]; 10 , 180 , 300 , 30 ) ; bottone.frame = CGRectMake (10, 180, 300, 30); @ "Premi qui" forState : UIControlStateNormal ] ; [Button setTitle: @ "Click Here" Forst: UIControlStateNormal]; self action : @selector ( controllaNumero ) forControlEvents : UIControlEventTouchUpInside ] ; [AddTarget button: self action: @ selector (getNumber) forControlEvents: UIControlEventTouchUpInside]; bottone ] ; [Window addSubview: button]; ; [MyLabel release]; ; [NavigationItem release]; ; [MyNavigationBar release]; |
della scorsa volta, subito dopo il [mainWindow release]; inseriamo: Since the ' applicationDidFinishLaunching corresponds to viewDidLoad as last time, just after the [mainWindow release]; insert:
1 | + arc4random ( ) % 10 ; numeroACaso arc4random = 1 + () 10%; |
Now we can do is implement the method controllaNumero , which will be identical (apart from the prototype) to that used last time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | void ) controllaNumero { - (Void) {getNumber "Premuto bottone di controlla numero" ) ; NSLog (@ "Pressed button control number"); [ numero.text integerValue ] ; numeroInserito = int [numero.text integerValue]; message; NSString * message; "Il numero inserito è %d" , numeroInserito ) ; NSLog (@ "The number entered is% d", numeroInserito); numeroInserito <numeroACaso ) { if (numeroInserito <numeroACaso) { "Troppo basso..." ; message = @ "Too low ..."; ( numeroInserito> numeroACaso ) { } Else if (numeroInserito> numeroACaso) { "Troppo alto..." ; message = @ "Too high ..."; ( numeroInserito == numeroACaso ) { } Else if (numeroInserito numeroACaso ==) { "Bravo hai indovinato" ; message = @ "Bravo, you guessed it"; + arc4random ( ) % 10 ; numeroACaso arc4random = 1 + () 10%; "Numero pensato %d" , numeroACaso ) ; NSLog (@ "Number% d thought," numeroACaso); } [ [ UIAlertView alloc ] UIAlertView alertMessaggio * = [[UIAlertView alloc] "Responso" initWithTitle: @ "Response" message: message delegate: nil "OK" cancelButtonTitle: @ "OK" ] ; otherButtonTitles: nil]; ; [AlertMessaggio show]; ; [AlertMessaggio release]; "" ; numero.text @ = ""; } |
We're done!
Conclusions and considerations
, proprio perchè volevo lasciarlo il più semplice e snello possibile e, anche, per dimostrare che non sono elementi sempre necessari. This example does not make direct use of a UIView or UIViewController , just because I wanted to leave it as simple and streamlined as possible and, also, to show that the elements are not always necessary. However insert objects directly in the window can have some sense in this example and other sporadic contexts. portano comunque benefici in tantissimi altri casi, ein alcuni sono praticamente indispensabili; come avremo modo di vedere in futuro. The use of UIView and UIViewController bring benefits in many other cases, however, some are virtually indispensable ein, as we will see in the future.
XCode: organize your code with the # pragma mark
XCode is a very powerful and versatile and provides the programmer with many useful features and simple to use. When writing complex code, or at least articulated, it becomes important to organize your code so you do not waste time searching functions spread in long lines of code. After commenting, the first and most important thing to do, the environment XCode provides guidelines (nice) to improve the usability and legginilità within the development. One of these is the directive #pragma mark that becomes very useful in organizing groups of the code and methods.
In the picture below you can see the code part of my project PragmaTest :

The top dropdown menu allows you to list all the methods of our class. Now if we insert our method over the directive #pragma mark which has a syntax:
1 | # Pragma mark {label} |
We get:

The first #pragma mark with a hyphen (-) inserts a separator line. The second is a text (label) to taste. You can add the following statement where you want, organizing the code as you see fit. You can enter more pragmatic lines, type:
1 2 3 4 5 6 | # Pragma mark - # Pragma mark / ** # Pragma mark * Using the pragma # Pragma mark * on several lines of code # Pragma mark * / void ) mioMetodo { } - (Void) {} myMethod |
Apple iPhone: The First Release 1.2

Available on the AppStore update to the 1.2 release of thefirst . Here are the release notes:
- Fully revised throughout the game's graphics, which is now much more pleasant
- Compatible with Apple iPhone 3.0
- Added sound effects
- Revised and improved the navigability of the game and instructions
iPhone: all system fonts
The Apple iPhone provides a limited number of fonts to developers. The list of available fonts is easily achieved by code, as we shall see. If you want to use your own fonts, such as including it in the resources, it is a little more articulate and conivolge also the issue of licenses (rights) fonts "embed" ... we'll talk later. Turning instead to the official sources present in the iPhone they are (click on image to enlarge):
The Apple iPhone SDK provides access to the special system fonts. These are identified by special constants and are:
1 2 3 | [ UIFont boldSystemFontOfSize : 12.0 ] ; UIFont myBoldFont * = [UIFont boldSystemFontOfSize: 12.0]; [ UIFont SystemFontOfSize : 12.0 ] ; UIFont mySystemFont * = [UIFont SystemFontOfSize: 12.0]; [ UIFont italicSystemFontOfSize : 12.0 ] ; UIFont myItalicFont * = [UIFont italicSystemFontOfSize: 12.0]; |
If you actually get a pointer to a odei fonts shown in the image above just use:
1 | [ UIFont fontWithName : @ "Helvetica-Bold" size : 22.0 ] ; UIFont myCustomFont * = [UIFont fontWithName: @ "Helvetica-Bold" size: 22.0]; |
As you can see the management of the font is special, in addition to the family (Helvetica, Courier, etc ...) must specify the type (bold, italic, etc ...). In practice, therefore, a font must be equipped with these features. The Helvetica, for example, is represented by:
1 2 3 4 | Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique |
If you want to display your fonts directly on the iPhone, here are some useful code line:
1 2 3 4 5 6 7 8 9 10 11 12 | listOfFonts = [ [ NSArray alloc ] initWithArray : [ UIFont familyNames ] ] ; NSArray * listOfFonts = [[ NSArray alloc] initWithArray: [UIFont familyNames]]; subFontTypes; NSArray * subFontTypes; int i = 0 ; i< [ listOfFonts count ] ; i ++ ) { for (int i = 0; i <[listOfFonts count]; i + +) { "Font Family: %@" , [ listOfFonts objectAtIndex : i ] ) ; NSLog (@ "Font Family:% @", [listOfFonts objectAtIndex: i]); NSArray alloc ] initWithArray : [ UIFont fontNamesForFamilyName : [ listOfFonts objectAtIndex : i ] ] ] ; subFontTypes = [[ NSArray alloc] initWithArray: [UIFont fontNamesForFamilyName: [listOfFonts objectAtIndex: i]]]; int j = 0 ; j< [ subFontTypes count ] ; j ++ ) { for (int j = 0 j <[subFontTypes count] j + +) { "+----->Type: %@" , [ subFontTypes objectAtIndex : j ] ) ; NSLog (@ "+-----> Type:% @ ", [subFontTypes objectAtIndex: j]); } ; [SubFontTypes release]; } ; [ListOfFonts release]; |
With the SDK 2.2.1 on my simulator, I got:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | Font Family: Courier +-----> Type: Courier +-----> Type: Courier-BoldOblique +-----> Type: Courier-Oblique +-----> Type: Courier-Bold Font Family: AppleGothic +-----> Type: AppleGothic Font Family: Arial +-----> Type: ArialMT +-----> Type: Arial-BoldMT +-----> Type: Arial-BoldItalicMT +-----> Type: Arial-ItalicMT Font Family: sthe TC +-----> Type: Light-STHeitiTC +-----> Type: Medium-STHeitiTC Font Family: Hiragino Kaku Gothic Pron +-----> Type: HiraKakuProN-W6 +-----> Type: HiraKakuProN-W3 Font Family: Courier New +-----> Type: CourierNewPS-BoldMT +-----> Type: CourierNewPS-ItalicMT +-----> Type: CourierNewPS-BoldItalicMT +-----> Type: CourierNewPSMT Font Family: Zapfino +-----> Type: Zapfino Font Family: Arial Unicode MS +-----> Type: ArialUnicodeMS Font Family: sthe SC +-----> Type: Medium-STHeitiSC +-----> Type: Light-STHeitiSC Font Family: American Typewriter +-----> Type: AmericanTypewriter +-----> Type: AmericanTypewriter-Bold Font Family: Helvetica +-----> Type: Helvetica-Oblique +-----> Type: Helvetica-BoldOblique +-----> Type: Helvetica +-----> Type: Helvetica-Bold Font Family: Marker Felt +-----> Type: Thin-MarkerFelt Font Family: Helvetica Neue +-----> Type: HelveticaNeue +-----> Type: HelveticaNeue-Bold Font Family: DB LCD Temp +-----> Type: DBLCDTempBlack Font Family: Verdana +-----> Type: Verdana-Bold +-----> Type: Verdana-BoldItalic +-----> Type: Verdana +-----> Type: Verdana-Italic Font Family: Times New Roman +-----> Type: TimesNewRomanPSMT +-----> Type: TimesNewRomanPS-BoldMT +-----> Type: TimesNewRomanPS-BoldItalicMT +-----> Type: TimesNewRomanPS-ItalicMT Font Family: Georgia +-----> Type: Georgia-Bold +-----> Type: Georgia +-----> Type: Georgia-BoldItalic +-----> Type: Georgia-Italic Font Family: sthe J +-----> Type: Medium-STHeitiJ +-----> Type: Light-STHeitiJ Font Family: Arial Rounded MT Bold +-----> Type: ArialRoundedMTBold Font Family: Trebuchet MS +-----> Type: TrebuchetMS-Italic +-----> Type: TrebuchetMS +-----> Type: Trebuchet-BoldItalic +-----> Type: TrebuchetMS-Bold Font Family: sthe K +-----> Type: Medium-STHeitiK +-----> Type: Light-STHeitiK |
How to delete NSLog () from source XCode
<a target="_blank" href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSLog">NSLog()</a> a useful function during the early stages of a project for testing and debugging an application for Apple iPhone or, more generally, in the XCode environment. Being just a function, just like the other, his presence will be felt even when releasing (release) our executable. potrebbero influire sulle performance della nostra applicazione, soprattutto se abbiamo inserito NSLog() all'interno di loop. It then becomes necessary to remove, in some way, all the rows in NSLog() out of our code, because it is no longer needed, and because calls to NSLog() could affect the performance of our application, especially if we put NSLog() to 'inner loop.
Immediately rule out the solution to the "look" and "cancel" because one day there could be used again. We exclude the solution of the "look" and "comments", uncomfortable for the same reason as before. Fortunately, a clean, simple, and are using the correct compiler conditionals. What we will do in practice, and tell the compiler to exclude - if there is a specific condition - when compiling our source lines that contain NSLog() .
The compiler directives and compiler conditional statements, are a very powerful and widespread. Those coming from the development of the ANSI-C knows very well and will definitely utilizzte in many situations. The peculiarity of these "instructions" lies in the fact, mentioned above, to be seen by the compiler and not executable. This feature makes them useful in many cases and can solve problems otherwise very annoying.
Let's see an example of code that, as predicted, you can "delete" from the compilation of code share, in our case NSLog() :
1 2 3 4 5 6 | # Define ACTIVE_NSLOG 1 / / If the constant is defined ACTIVE_NSLOG fill / / The block of code between # ifdef and # endif # Ifdef ACTIVE_NSLOG " ... bla bla" ) ; NSLog (@ "... blah blah"); # Endif |
). Conditional statements are part of the compiler of the same family as #define , also, in fact, are preceded by a "pound" ( # ). solo se ACTIVE_NSLOG è definito. In the example shown we have defined a constant ACTIVE_NSLOG ; subsequent lines of code tells the compiler to "include" line NSLog() only if ACTIVE_NSLOG is defined. If we took care, during the writing of our code, to place calls to NSLog() within the block #ifdef ... #endif per far sparire, alla prossima compilazione, tutti i nostri NSLog() . #ifdef ... #endif , just delete the definition of the constant ACTIVE_NSLOG to disappear, the next compilation, all our NSLog() .
A best and final
Let us now see how to set the XCode environment to improve even more what we have done here! First of all we choose a constant name that we use in our projects to exclude from the compilation NSLog() . o quello che preferite. You can choose the name that you like, from DEBUG to MIO_DEBUG or whatever you prefer. Open your project, new or old. Enter all the NSLog() within the block (or block):
1 2 3 | # Ifdef MIO_DEBUG " ... bla bla" ) ; NSLog (@ "... blah blah"); # Endif |
Select the main file of your project, click the right button and choose the Get Info item.

This opens the window with information about the project:

Select the Build tab, verify that you are in the Debug configuration (this is the gem), go to the User-Defined section and add, via the button at the bottom left, a new field called OTHER_CFLAGS . At this value assegnamoli -DMIO_DEBUG=1 . The syntax is -D{mia define}=1 .
This procedure has two advantages:
- We must not put in the code
#define MIO_DEBUG 1, but we do it through the project information. So, when we go to fill out the release version (the one without theNSLog()) do not have to remember to delete the line#define MIO_DEBUG 1 - The constant is defined in relation to the configuration, in our case Debug. So, switching to Release configuration (release) will be absent and the constant rows with
NSLog()will not be compiled
Conclusions
The above procedure may be useful in a moltidutine other cases, with NSLog() , have nothing to do. Conditional statements can help the compiler in a wide range of contexts. They are often used by programmers to determine the type of operating system, version, the target, the presence of mathematical processors, while maintaining the same "same" source.
To understand, as an example, we can utilizzre our constant MIO_DEBUG also intervene in other areas of the code:
1 2 3 4 5 6 7 8 9 10 | / / Debug if they win the game / / With a score of 100 instead of 10000:) # Ifdef MIO_DEBUG score == 100 ) if (score == 100) # Else score == 10000 ) if (score == 10000) # Endif { ; [HaiVinto self]; } |
To finish, here are some examples and variants:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | / / In general there is # If expression / / If statement similar to the traditional, so with a full expression / / Check if a constant is defined # Ifdef constant / / Check if it is NOT a constant defined # Ifndef constant / / Else # Else / / Close the block # Endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | / / For example ... # Define DEBUG 1 5 # define MIA_ALTRA_COSTANTE ... # If DEBUG / / Fill in this # Else / / Otherwise fill this other # Endif # If MIA_ALTRA_COSTANTE> 4 "..." ) ; NSLog (@ "..."); # Endif |
1 2 3 4 | # Ifndef INCLUDE_MIO_FILE # Define INCLUDE_MIO_FILE # Include "mio_file.h" # Endif |








Latest Comments
datrix : Thank you very much!
Robert : I rispsoto your questions with pleasure. The idea is really great. I am looking for a solution ...
Sting : @ Darius - you can see an example here: http://www.fight4fun.it/ clicking on: MAPS I hope ...
vik : Giustappunto I'm working on a project and the client asked me to show all the news (which are CPT) in ...
Giovambattista Fazioli : @ paso: absolutely. Simply identifying the field [cci] input [/ cci] you want to ...