Cocoa tutorial – linking and using libmysqlclient in your application

Here’s a little tutorial on how to use libmysqlclient in a Cocoa application.

First of all you need to create a new Xcode project; suppose to create it in the directory: /path/to/your/project/.

Then you need to retrieve the libmysqlclient.aand libmysqlclient_r.afiles located in the /usr/local/mysql/lib/default directory. To do this you can, for example, start a new Terminal session and type the following commands:

cp/usr/local/mysql/lib/libmysqlclient.a /path/to/your/project/cp/usr/local/mysql/lib/libmysqlclient_r.a /path/to/your/project/

Now go to Xcode and select “Project” -> “Edit Project Settings” in the main menu. Now select the “Build” tab and make the following changes to all your configurations (Debug and Release):

  • “Architectures”: the same of your libmysqlclient architecture;
  • “Valid Architectures”: architectures compatibles with your libmysqlclient architecture(s);
  • “C/C++ Compiler Version”: GCC 4.2;
  • uncheck “Prebinding”;
  • turn on (if desired) the “Objective-C Grabage Collection”;
  • “C Language Dialect”: C99 [-std=c99];
  • check “Mismatched Return Type”;
  • check “Unused Variables”.

Note that not all of these flags are strictly required for the correct use of libmysqclient.aand libmysqlclient_r.a; you can test them and see what happens when you change some of them.

Now you need to import the libraries. To do so, right click on the group “Frameworks” located in the “Groups & Files” tree in Xcode and select “Add” -> “Existing Frameworks…”. Locate the libmysqlclient.afile and click the Add button. Repeat the operation with the libmysqlclient_r.afile.

Now you need to tell Xcode to copy the two libraries in the bundle directory. To do so, you must create a new copy build phase in your target and put the libraries in it:

  • Expand the “Targets” group in the “Groups & Files” tree;
  • right click on your application and select: “Add” -> “New Build Phase” -> “New Copy Files Build Phase”;
  • in the new window select “Frameworks” in the Destination popup menu;
  • close the window;
  • drag and drop the libmysqlclient.aand libmysqlclient_r.afiles from the Frameworks group to the new “Copy Files” group.

Now you need to copy all the MySQL C API headers in your project directory. To do so you can, for example, do something like this:

cp-R/usr/local/mysql/include//path/to/your/project/mysql_include/

That’s all. To access any MySQL API function, you only need to import the mysql.hand unistd.h

Here’s a short example on how to use the API in a .m file:

... #include "mysql.h"#include "unistd.h"  @implementationAppController   ...   -(void)connect {MYSQL conn; mysql_init(amp;conn);   if(!mysql_real_connect(amp;conn, "127.0.0.1", "", "", "", 0, NULL, 0))NSLog(@"%s", [NSStringstringWithUTF8String:mysql_error(amp;conn)]); elseNSLog(@"Connected"); }@end

Download the test project.



출처 : http://blog.naver.com/PostView.nhn?blogId=ups999&logNo=150097675553
Posted by 오늘마감

댓글을 달아 주세요

아이폰어플개발정보2010. 10. 30. 19:26
[아이폰 앱 개발] Application Frame얻기

Application Frame
Use "bounds" instead of "applicationFrame" -- the latter will introduce a 20 pixel empty status bar (unless you want that..)
Posted by 오늘마감

댓글을 달아 주세요

아이폰어플개발정보2010. 10. 12. 05:57
Application Frame얻기

Application Frame
Use "bounds" instead of "applicationFrame" -- the latter will introduce a 20 pixel empty status bar (unless you want that..)

'아이폰어플개발정보' 카테고리의 다른 글

UIBarButtonItem을 viewDidLoad에서 만들고 숨기기  (0) 2010.10.12
Display Images  (0) 2010.10.12
Application Frame얻기  (0) 2010.10.12
A basic UIWebView  (0) 2010.10.12
Animation: Move an object  (0) 2010.10.12
Info button  (0) 2010.10.12
Posted by 오늘마감

댓글을 달아 주세요

아이폰어플개발정보2010. 6. 24. 14:13
iPhone Application Programming Guide

Ch1. The Core Application

The delegate object can be an instance of any class you like, as long as it adopts the UIApplicationDelegate protocol.

If the application’s information property list (Info.plist) file contains the NSMainNibFile key, the UIApplication object loads the nib file specified by that key as part of its initialization process.

The main nib file of an iPhone application typically contains a window object, the application delegate object.


In the iPhone OS Multi-Touch event model, touch data is encapsulated in a single event object (UIEvent). To track individual touches, the event object contains touch objects (UITouch), one for each finger that is touching the screen.


You can install your own input sources, including ports and timers, on a run loop using the NSRunLoop class of the Foundation framework.


If your application takes more than 5 seconds to quit, the system may terminate it outright.


Application Sandbox

Application's home directory is /ApplicationRoot/ApplicationID/

ApplicationID: a unique opaque ID computed by system, when the application is installed


To disable the timer, set the idleTimerDisabled property of the shared UIApplication object to YES.


 A bundle is a directory in the file system that groups related resources together in one place.

- MyApp: executable file

- Settings.bundle: used to add application preferences to the Settings application.

- Icon.png: 57x57 pixel icon displayed on the home screen

- Icon-Settings.png: 29x29 pixel icon displayed in the Settings application

- Default.png: The 480 x 320 pixel image to display when your application is launched.

- iTunesArtwork:512x512 icon for an application that is distributed using ad-hoc distribution.

- Info.plist: information property list

- other resource files

- en.lproj, ... : other localized resources


// loading localized resources example

NSString* imagePath = [[NSBundle mainBundle] pathForResource:@"sun" ofType:@"png"];

UIImage* sunImage = [[UIImage alloc] initWithContentsOfFile:imagePath];


// Important Keys in the Info.plist

CFBundleDisplayNameThe name to display underneath the application icon.

CFBundleIdentifier: UTI, ex) com.Ajax.Hello

The bundle identifier is used in validating the application signature.

CFBundleURLTypes: An array of URL types that the application can handle (http, mailto, ...)  This property allows applications to register custom URL schemes.

UIStatusBarStyle: A string that identifies the style of the status bar as the application launches.

UIStatusBarHidden: determines whether the status bar is initially hidden when the application launches

UIPrerenderedIconindicates whether the application icon already includes gloss and bevel effects

UIRequiresPersistent-WiFiApplications that use Wi-Fi for any period of time must set this key to true; otherwise, after 30 minutes, the device shuts down Wi-Fi connections to save power.


String value in Info.plist should be a key to a localized string in the InfoPlist.strings file of a language-localized subdirectory.


Default.png should closely resemble the application’s initial userinterface; the system displays the launch image before an application is ready to display its user interface, giving users the impression of a quick launch.


A nib file is a data file that stores a set of “freeze-dried” objects that the application plans to use later. The nib-loading code turns the contents into real objects that your 

application can manipulate.


If your application uses view controllers, the view controller handles the nib loading process for you automatically but you can also load nib files your self using the methods of the NSBundle class.


UIApplicationDelegate protocol

applicationDidFinish-Launching:        // custom init.

applicationWillTerminate:                // save unsaved data, cleanup


** Interruption **

The Home button terminates your application. If the user  decides to take a call or reply to an SMS message, or calendar events, however, the system does proceed to terminate your application.


applicationWillResignActive:            // phone call, sleep

applicationDidBecomeActive:           // user not answer the call, wakeup

applicationWillTerminate:               // user answers the call


When the user takes a call and then relaunches your application while on the call, the height of the status bar grows to reflect the fact that the user is on a call.

layoutSubviews // handle dynamic layout changes...


UIKit provides several ways to receive low-memory notifications

 ■ Implement the applicationDidReceiveMemoryWarning: method of your application delegate. 

 ■ Override the didReceiveMemoryWarning method in your custom UIViewController subclass. 

 ■ Register to receive the UIApplicationDidReceiveMemoryWarningNotification notification.


UIInterfaceOrientation key == Using this key is also equivalent to calling the setStatusBarOrientation:animated: method of UIApplication early in the execution of your applicationDidFinishLaunching: method.


Registering custom URL schemes - CFBundleURLTypes

Your application delegate is sent a application:handleOpenURL: message.


A settings bundle is a custom resource you include in the top level of your application’s bundle directory. Settings.bundle. Your application then accesses using the NSUserDefaults or CFPreferences APIs.

(Icon-Settings.png icon file with 29x29 PNG file)


** internationalization **

NSString *NSLocalizedString(NSString *key, NSString *comment);

ex) label.text = NSLocalizedString(@"City", @"Label for City text field");

in the lproj folder

"City" = "Ville";


Or use genstrings command-line tool to generate Localizable.strings template from source code.


** Reduce your application's memory footprint **

+ eliminate memory leak

+ make resource files as small as possible.

 - property files in binary format using NSPropertyList-Serialization class

 - compress PNG images using pngcrush tool.

+ use SQLite for large data sets

+ load resources lazily

+ Adding the -mthumb compiler flag can reduce the size of your code by up to 35% (but it can also cause degrade the performance of floating-point code)


** allocate memory wisely **

+ avoid using the autorelease method when you can instead use the release

+ rather than load the entire file into memory, use the mmap and munmap functions

+ avoid unbounded problem sets


** reduce power consumption **

+  accessing the network is the most power-hungry operation

 - Transmit data in bursts rather than spreading out transmission packets overtime.

- Core Location uses the available GPS, cell, and Wi-Fi networks.


Ch2. Windows and Views


iPhone applications typically have only one window,  represented by an instance of the UIWindow class.


In Mac OS X, the parent class of NSWindow is NSResponder. In iPhone OS, the parent class of UIWindow is UIView.


You should always set its application window size to fill the entire screen.

UIWindow* aWindow = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

Your application should never create more than one window.


A view, an instance of the UIView class, defines a rectangular area on the screen.

- render content within its rectangular area

- respond to touch events in that area


view hierarchy may contain any number of views.

Each parent view is responsible for managing its direct subviews, by adjusting their position and size as needed and even responding to events that its subviews do not handle.


** UIKit interactions **

1. The user touches the screen.

2. The hardware reports the touch event to the UIKit framework.

3. The UIKit framework packages the touch into a UIEvent object and dispatches it to the appropriate view.

4. The event-handling methods of your view responds to the event.

5. If a view is marked as requiring layout, UIKit calls the view’s layoutSubviews method.

6. If any part of the view is marked as needing to be redrawn, UIKit calls the view’s drawRect: method.

7. Any updated views are composited with the rest of visible content and sent to the graphics hardware for display. 

8. The graphics hardware transfers the rendered content to the screen.


In contrast with Mac OS X (in which Core Animation support is optional) iPhone OS integrates Core Animation into the heart of the view rendering implementation.


Core Animation stores the layers ( CALayer object) associated with your view objects in a hierarchy referred to as the layer tree. You can add layers, however, without adding a corresponding view.

- presentation tree: reflects the state of the layers as they are currently presented to the user.

- render tree: a private API


** properties of view objects **

- frame rectangle: specifies it relative to its parent view's coord.

- bounds rectangle: relative to its local coord. system (inside the image data, etc)

- center point: center of the frame


If the transform property is not the identity transform, the value of the frame property is undefined and must be ignored. After setting the transform, use the bounds and center properties to get the position and size of the view.


content mode

- Scale to fill (distorting)

- Aspect Fit

- Aspect Fill


autoresizesSubviews property: NO (default)

applications can override  layoutSubviews method.


For autoresizing to work correctly, the view’s transform property must be set to the identity transform. The behavior is undefined if it is not.


You must add views to a window or to another view to make them appear on the screen.


**  common places to create views and subviews programmatically **

- applicationDidFinishLaunching: of application delegate

loadView of view controllers


Because parents retain their subviews, this method (applicationDidFinishLaunching:) releases the newly created views to prevent them from being overretained.


The UIView class contains a tag property.  Tag-based searches are faster than iterating the view hierarchy yourself.


An animation block starts with a call to the beginAnimations:context: class method of UIView and ends with a call to the commitAnimations class method.  As soon as you call the commitAnimations

method, UIKit performs the animations.


The current graphics context is valid only for the duration of one call to your view’s drawRect: method. UIKit may create a different graphics context for each subsequent call to this method, so you should not try to cache the object and use it later.


The UIView class is a subclass of UIResponder.


To prevent events from reaching any of your views, you can also use the beginIgnoringInteractionEvents and endIgnoringInteractionEvents methods of the 

UIApplication object.


Ch3. Event Handling


An event is an object that the system continually sends to an application as fingers touch the screen and move across its surface.


* Phase *

- UITouchPhaseBegan

- UITouchPhaseMoved

- UITouchPhaseEnded


An event object ( UIEvent) contains all touch objects (UITouch) for the current multi-touch sequence and can provide touch objects specific  to a view or window.

Cancellations can occur as a result of overriding system events, such as an incoming phone call.


The singleton UIApplication object that is managing the application takes an event from the top of the queue and dispatches it for handling. Anapplication uses hit-testing to find the first responder for an event; it recursively calls hitTest:withEvent: on the views in the view hierarchy.


The UIApplication object and each UIWindow object dispatches events in the sendEvent: method. If the application finds no responder object to handle the event,  it discards the event.


A responder may decline to handle a particular event or may handle it only partially. In that case,  it can forward the event message to the next responder.

[self.nextResponder touchesBegan:touches withEvent:event];


* responder object must implement at least one of these methods *

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event


Custom views that redraw themselves in response to events they handle generally should only set drawing state in the event-handling methods and perform all of the drawing in the drawRect: method.


Ch4. Graphics and Drawing

- OpenGL frameworks are geared primarily toward game development or applications that require high frame rates.

- Quartz is the main drawing interface, providing support for 

path-based drawing, anti-aliased rendering, gradient fill patterns, images, colors, coordinate-space transformations, and PDF document creation, display, and parsing. (lower-left corner origin)

- UIKit provides Objective-C wrappers for Quartz images and color manipulations.

- Core Animation provides the underlying support for animating changes in many UIKit view properties and can also be used to implement custom animations.


** trigger a view update **

 ■ Moving or removing another view that was partially obscuring your view 

 ■ Making a previously hidden view visible again by setting its hidden property to NO

 ■ Scrolling a view off the screen and then back on 

 ■ Explicitly calling the setNeedsDisplay or setNeedsDisplayInRect: method of your view


Current Transformation Matrix (CTM): mathematical matrix that maps points in your view’s coordinate system to points on the device’s screen.


Creating paths is a relatively expensive operation, but creating a square whose origin is at (0, 0) and modifying the CTM to match the desired drawing origin is cheap by comparison.


- user coordinate space: drawing commands in Quartz are specified using a fixed-scale drawing space

device coordinate space: 1 point equaling 1/160th of an inch


Your drawing code should always use RGB colors.


UIGraphicsGetCurrentContext function returns a reference to a CGContextRef type.

CGContextSaveGState and CGContextRestoreGState push and pop graphics states.


** images usage scenarios **

- Display an image as the content of a view: UIImageView class

- Display an image as an adornment for part of a view: UIImage class

- Save some bitmap data into an image object:  UIGraphicsBeginImageContext function /  CGBitmapContextCreate function

- Save an image as a JPEG or PNG file:  UIImageXXXXRepresentation function on UIImage object


GPU in iPhone is PowerVR MBX Lite

: TBDR (Tile Based Deferred Rendering), vs. streaming renderers

: The frame buffer is divided up into a number of tiles, and the scene is drawn once for each tile, each time drawing only the content that is actually visible within that tile.


You should try to draw as much of the scene with opaque content as possible and minimize use of blending and alpha 

testing.


You should always profile and optimize your drawing code on a real device and not assume that the simulator reflects real-world performance.


On a device, OpenGL ES applications can use no more than 24MB of memory for both textures and surfaces. The simulator does not enforce this limit.


Core Animation is a technology for manipulating and displaying content that you created using other technologies.


Ch5. Text and Web

iPhone OS sends out the following notifications to any registered observers:

UIKeyboardWillShowNotification

UIKeyboardDidShowNotification

UIKeyboardWillHideNotification

UIKeyboardDidHideNotification


Each keyboard notification includes information about the size and position of the keyboard on the screen. You should always use the information in these notifications.


Ch6. Files and Networking


* directories under the Application_home *

- AppName.app/ : don't change the contents of this directory

+ Documents/ : data directory backed up by iTunes

+ Library/Preferences/ : use the NSUserDefaults class, backed up by iTunes

- Library/Caches/ : persistent data between launch

- tmp/ : temporary directory. You should remove files from this directory


NSHomeDirectory function: returns top level home directory in NSString

- NSTemporaryDirectory


If your application contains sound, image, or other resources in the application bundle, you should use the NSBundle class or CFBundle opaque type to load those resources.


* Reading and writing

+ Foundation Framework

- NSData object: represented as a property list, convert using NSPropertyListSerialization API

- NSKeyedArchiver class: if your application model adopts NSCoding protocol

- NSFileHandle class: random access

- NSFileManager class: manage files in the file system

+ Core OS calls

- fopen(), fread(), fwrite()

- mmap(), munmap(): load large files


property list: keys (NSString) + values (NSDictionary, NSArray, NSString, NSDate, NSData, andNSNumber)


read and write using NSPropertyListSerialization class.


* Avoid writing cache files to disk except state information


The Bonjour system service does immediately invoke browsing callbacks when it receives a notification that a service is going away, but network services can disappear without notification.


UIRequiresPersistentWiFi key in the application’s Info.plist file  lets the system know that it should not attempt to shut down the Wi-Fi hardware while your application is running.


Ch7. Multimedia Support

To play alerts and user-interface sound effects: System Sound Services

To play sounds in the fewest lines of code: AVAudioPlayer class

To provide full-featured audio playback: OpenAL

To provide lowest latency audio: I/O audio unit

To play sounds with the highest degree of control: Audio Queue Services

To record audio: Audio Queue Services

To parse audio streamed from a network connection: Audio File Stream Services


hardware codec employed for playback

AAC 

ALAC(AppleLossless) 

MP3 

The device can play only a single instance of one of these formats at a time.

While the first one is being played using HW codec, the second and thereafter of any of these codec files will be played using SW codec.


To play multiple, high-quality sounds, or to play sounds while the iPod is playing in the background, use linear PCM (uncompressed) or IMA4 (compressed) audio.


*audio playback formats supported

 ■ AAC 

 ■ AMR (Adaptive Multi-Rate, a format for speech) 

 ■ ALAC (Apple Lossless) 

 ■ iLBC (internet Low Bitrate Codec, another format for speech) 

 ■ IMA4 (IMA/ADPCM) 

 ■ linear PCM (uncompressed) 

 ■ μ-law and a-law 

 ■ MP3 (MPEG-1 audio layer 3)

* audio recording formats supported

 ■ ALAC (Apple Lossless) 

 ■ iLBC (internet Low Bitrate Codec, for speech) 

 ■ IMA/ADPCM (IMA4) 

 ■ linear PCM 

 ■ μ-law and a-law 


** Sounds played with System Sound Services are not subject to configuration using your audio session.


* AudioServicesPlaySystemSound function

- Shorter than 30 seconds in duration 

- In linear PCM or IMA4 (IMA/ADPCM) format 

- Packaged in a .caf, .aif, or .wav file

- Sounds play at the current system audio level, with no level control available 

 - Sounds play immediately 

- Looping and stereo positioning are unavailable 


System-supplied alert sounds and system-supplied user-interface sound effects are not available to your application. For example, using the kSystemSoundID_UserPreferredAlert constant as a parameter to the AudioServicesPlayAlertSound function will not play anything.


1. AudioServicesCreateSystemSoundID()

2. AudioServicesPlaySystemSound()

to vibrate

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);


** AVAudioPlayer class

- simple

- any duration

- from files or memory buffers

- loop sounds

- multiple sounds simultaneously

- control relative playback level for each sound

- seek to a particular point

- obtain audio power data

- no stereo positioning / precise synch., network stream


** Audio Queue Services

- beyond AVAudioPlayer class

- precise scheduling with synch.

- precise volume control

- from stream using Audio File Stream Services


OpenAL is your best choice for playing sound effects in game applications on iPhone OS–based devices. (see oalTouch sample code)


For recording, refer to the SpeakHere sample code.


iPhone OS provides a set of audio plug-ins, known as audio units, that you can use in any application. (static linked to your app.)


** Preferred Audio formats in iPhone **

 ■ uncompressed: 16-bit, little endian, linear PCM audio data packaged in a CAF file.

afconvert -f caff -d LEI16 {INPUT} {OUTPUT}

 ■ compressed (not simultaneous): AAC format in CAF or m4a file

 ■ less memory (simultaneous): IMA4 data in CAF file


** playing video files

iPhone OS supports the ability to play back video files directly from your application using the Media Player framework (MediaPlayer.frameworkfull screen mode only!!


+ supported files: .mov, .mp4, .m4v, and .3gp filename extensions with following compression methods

- H.264 Baseline Profile Level 3.0 video, up to 640 x 480 at 30 fp

- MPEG-4 Part 2 video (Simple Profile)


Ch8. Device Support

- HW features: accelerometer, camera

- SW features: photo library


accelerometer reporting interval: 10 msec. ~


To stop the delivery of acceleration events, set the delegate of the shared UIAccelerometer object to nil.


Before getting the current orientation, you must tell the UIDevice class to begin generating device orientation notifications by calling the beginGeneratingDeviceOrientationNotifications method. Doing so turns on the accelerometer hardware.


Checking the timestamp of an event is recommended because the location service often returns the last cached location event immediately.


As you do for the camera picker, you should always call the isSourceTypeAvailable: class method of the UIImagePickerController class and respect the return value of the method.


Ch9. Application Preferences

* Directory structure

Settings.bundle in the top-level directory of your application’s bundle

Root.plist

Additional .plist files

.lproj directories

Icon-Settings.png: 29 x 29 pixel image


* Preference element types

- Text Field:       PSTextFieldSpecifier

- Title:               PSTitleValueSpecifier

- Toggle switch: PSToggleSwitchSpecifier

- Slider:             PSSliderSpecifier

- Multi value:     PSMultiValueSpecifier

- Group:            PSGroupSpecifier

- Child pane:      PSChildPaneSpecifier


* Accessing preference values in an application 

- (void)applicationDidFinishLaunching:(UIApplication *)application

{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [self setMyAppBoolProperty:[defaults boolForKey:MY_BOOL_PREF_KEY]];

    // Finish app initialization...

}


Each time you reinstall your application, iPhone OS performs a clean install, which deletes any previous preferences.



출처 : http://blog.naver.com/PostView.nhn?blogId=gonagi&logNo=150046760690

'아이폰어플개발정보' 카테고리의 다른 글

iPhone Cool Projects  (0) 2010.06.24
OpenGL ES Progg Guide for iPhone  (0) 2010.06.24
iPhone Application Programming Guide  (0) 2010.06.24
iPhone Human Interface Guidelines  (0) 2010.06.24
iPhone Games Projects  (0) 2010.06.24
The iPhone Developers Cookbook  (0) 2010.06.24
Posted by 오늘마감

댓글을 달아 주세요