아이폰어플개발정보2010. 6. 24. 14:13
Beginning iPhone Development: Exploring the iPhone SDK

CH2. Appeasing the Tiki Gods


In each Nib file (File’s Owner and First Responder), every icon in this window represents a single instance of an  Objective‑ C class that will be created automatically for you when this nib file is loaded. 


File’s Owner: represents the object that loaded the nib file from disk

First Responder: the object with which the user is currently interacting. The first responder changes as the user interacts with the interface.


AppKit (Mac OS X) --- UIKit (iPhone OS)


CH3. Handling Basic Interaction


MVC model - Any object you write should be readily identifiable as belonging in one of the three categories for maximum reusability.


outlet: (IBOutlet) a pointer that points to an object within the nib

IBOutlet keyword in the header files allows IB to make connections from your code to the nib.


action: (IBAction) part of controller class. 


class methods: factory methods, returns an autoreleased object


“if you didn’t allocate it or retain it, don’t release it”


UIViewController --- corresponding nib file

MainWindow.xib --- in Info.plist -- ApplicationDelegate


Your controller class is the file’s owner for the nib file of the same name.


** connecting outlets **

By  control‑ dragging from File’s Owner to an interface object, you are telling Interface Builder that you want to connect one of the File’s Owner’s outlets to this object when the nib file is loaded.


** specifying actions **

The only thing left to do is to identify which actions these buttons trigger and under what circumstances they trigger them.


 Up Inside.  In most of your iPhone applications if you touch the screen and change your mind. You move your finger off the button before lifting up, right? We should give our users the same ability. If our user’s finger is still on the button when it’s lifted off the screen, then we can safely assume that the button tap is intended.


Ch4. More User Interface Fun


* Controls can be used in many ways.

- active: button, ...

- static: label, ...

- passive: e.g., text field, ...


The way to access the data held by a passive control is to use an outlet.


If you want to display the same image at multiple sizes, generally it’s better to have multiple copies of the image at different sizes in your project rather than force the iPhone to do scaling at runtime.


Tags provide an easy,  language-independent way of identifying objects on your interface. The system will never set or change its value.


Opaque: nothing below this view ever needs to be drawn no matter what.

Clip Subviews: is off by default for the sake of performance


When the user taps the Done button, a “did end on exit” event will be generated.

First responder is the control that the user is currently interacting with. When a text field yields first responder status, the keyboard associated with it goes away.


action sheet - <UIActionSheetDelegate>

All action sheets should have a cancel button.

In situations where you want to notify the user without giving a choice of options, an alert sheet (alert view?) is more appropriate.

Action sheets always have a parent, which must be a view that is currently visible to the user. .


* 4 states of a control

- normal: rest of the other three

- highlighted: when it is being used

- disabled

- selected


Ch5. Autorotation and Autosizing


* tackling autorotation

- autosizing

- manually reposition each object

- different view versions for each rotation


* 4 possible roation

- UIInterfaceOrientationPortrait 

- UIInterfaceOrientationPortraitUpsideDown 

- UIInterfaceOrientationLandscapeLeft 

- UIInterfaceOrientationLandscapeRight 


Because every view controller subclass can implement this differently, it is  possible for one application to support autorotation with some of its views but not with others.


Transformations are mathematical descriptions of changes to an object’s size, position, or angle.


Ch6. Multiview Applications


UITabBarController and UINavigationController are subclasses of UIViewController and can do anything other view controllers can do.


A content view is created indirectly by instantiating its controller class and specifying a nib name. Nibs are typically named using the same name as the controller class.


The root controller gets created when the application loads MainWindow.xib.


The window is the only gateway to the user, so anything that needs to be displayed to the user has to get added as a window subview.


Lazy Loading: do not load resources in the viewDidLoad: method until they are actually needed. ** Loading resources on-demand allows us to freely deallocating those resources when low memory situation occurs. **


** When we changed the underlying class of the file’s owner, the existing outlet connections were broken.  **


**Animation Example**


[UIView beginAnimations:@"View Flip" context:nil]; 

[UIView setAnimationDuration:1.25]; 

[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 

[UIView setAnimationTransition: transition forView:self.view cache:YES]; 

[coming viewWillAppear:YES]; //#1

[going viewWillDisappear:YES]; //#1

[going.view removeFromSuperview]; 

[self.view insertSubview: coming.view atIndex:0]; 

[going viewDidDisappear:YES]; //#1

[coming viewDidAppear:YES]; //#1

[UIView commitAnimations]; 


#1: Views that have running animations on them, for example, will often choose to turn those animations off when their view is swapped out and turn them back on when they are swapped back in.


Ch7. Tab Bars and Pickers


The picker asks the delegate for either a string or a view that will be drawn at a given spot on a given component.

Picker datasource methods are used by the picker to get the number of components and the number of rows in each component. The datasource isn’t usually an object designed to hold data; it’s an object that supplies data to the picker.


Tab Bar icons - 24x24 pixels in .png format


* Using Interface Builder

1. Declare var.s in Header file

2. Draw controls and set up the classes and properties

3. Implement the Method file


We use NSInteger rather than int or long, because when we use NSInteger, the compiler automatically chooses whichever size is best for the platform for which we are compiling.


Putting in #pragma mark directives and logically organizing your code will make that  pop- up more efficient to use.


bundle is just a special type of folder whose contents follow a specific structure. Applications and frameworks are both bundles.


** fonts on iPhone **

American TypewriterAppleGothicArialArial Rounded MT BoldArial Unicode MS,CourierCourier New, DB LCD Temp, Georgia, Helvetica, Helvetica NeueHiragino Kaku Gothic ProN W3Hiragino Kaku Gothic ProN W6Marker FeltSTHeiti JSTHeiti KSTHeiti SCSTHeiti TCTimes New RomanTrebuchet MSVerdanaZapfino


** convenience class methods use the autorelease pool.


NSString *path = [[NSBundle mainBundle] pathForResource:@"crunch" ofType:@"wav"]; 

SystemSoundID soundID; 

AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID); 

AudioServicesPlaySystemSound(soundID);


Ch8. Introduction to Table Views

A table view is the object that displays the visible part of a table, and a table view cell is responsible for displaying a single row of the table.


Table views get their configuration data from an object that conforms to the UITableViewDelegate protocol and their row data from an object that conforms to the UITableViewDataSource protocol.


* 2 methods that implement the UITableViewCell

- add subviews to UITableViewCell

- subclass UITableViewCell


* 2 types of table view

- grouped table

- indexed (with or without index)


section: group in a table


Mutable copy: shallow copy


It is not safe to remove objects from a collection while iterating that collection.


It’s very important to avoid using convenience methods inside of loops as much as possible, because they will put something into the autorelease pool every time through the loop. However, the autorelease pool can’t get flushed until we’re all done with our loop.


Ch9. Navigation Controllers and Table Views


UINavigationController is implemented as a stack

disclosure indicator vs. detail disclosure control


If tapping a row takes you to another view entirely, one that is not a more detailed view of that row, use a disclosure indicator (gray arrow) to mark the row. 


** 6 styles of cell **

+ Detail Disclosure button

// showing disclosure button

- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath 

    return UITableViewCellAccessoryDetailDisclosureButton; 

}

// responding disclosure detail button

- (void)tableView:(UITableView *)tableView 

accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath 


+ Checked

newCell.accessoryType = UITableViewCellAccessoryCheckmark;


+ Adding Controls

// add control to the accessory pane

UISwitch *switchControl = [[UISwitch alloc] init];

switchControl.tag = kSwitchTag;

cell.accessoryView = switchControl;


// read value

UISwitch *switchControl = [cell viewWithTag:kSwitchTag];


+ Editing mode

setEditing:animated: method on the table view.


reordering for cell

cell.showsReorderControl = YES;


+ Delete mode

The delete and reorder operations do play nicely together.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath


We can’t store raw datatypes like int in an NSDictionary.


Ch10. Application Settings and User Defaults


NSUserDefaults class

There can only be one root node in any given property  list, and all nodes must come under it.

Although you can use any kind of object as a key in an NSDictionary, keys in property list dictionary nodes have to be strings, though you are free to use any node type for the values.


Sliders allow placement of a small  21- pixel   21- pixel image at each end of the slider.


* Type *

PSGroupSpecifier

PSTextFieldSpecifier

PSTextFieldSpecifier

PSMultiValueSpecifier

PSToggleSwitchSpecifier

PSSliderSpecifier

PSChildPaneSpecifier


NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

objectForKey:, intForKey:, floatForKey: boolForKey:


Ch11. Basic Data Persistence


NSSearchPathForDirectoriesInDomain function


* Document directory *

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

NSString *documentsDirectory = [paths objectAtIndex:0];

// each application has only one Documents directory.

NSString *filename = [documentsDirectory  stringByAppendingPathComponent:@"/theFile.txt"];


* Temporary directory *

NSString *tp = NSTemporaryDirectory();


The downside of using a single file is that you have to load all of your application’s data into memory, and you have to write all of it to the file system for even the smallest changes.


** Property list serialization

Although any object can be made serializable, only certain objects can be placed into a collection class, such as an NSDictionary or NSArray, and then stored to a property list using the collection classes’ writeToFile:atomically: method. 

- NSArray

- NSMutableArray

- NSDictionary

- NSMutableDictionary

- NSData

- NSMutableData

- NSString

- NSMutableString

- NSNumber

- NSDate


[myArray writeToFile:@"/some/file/location/output.plist" atomically:YES];


** Archiving model object

* NSCoding protocol *

You can encode and decode both objects and scalars using  key- value coding.

- (void)encodeWithCoder:(NSCoder *)encoder

- (id)initWithCoder:(NSCoder *)decoder

// if your superclass doesn't conform to NSCoding

   if (self = [super init])

// if your superclass conforms to NSCoding

   if (self = [super initWithCoder:decoder])


* NSCopying protocol *

- (id)copyWithZone:(NSZone *)zone

{

    MyClass *copy = [[[self class] allocWithZone: zone] init];

    copy.foo = [self.foo copy];

   ...

    return copy;// caller releases copy

}


* Archiving Data object *

NSMutableData *data = [[NSMutableData alloc] init];

NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

[archiver encodeObject:myObject forKey:@"keyValueString"];

[archiver finishEncoding];

BOOL success = [data writeToFile:@"/path/to/archive" atomically:YES];

[archiver release];

[data release];

* Unarchiving Data object *

NSData *data = [[NSData alloc] initWithContentsOfFile:path];

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

self.object = [unarchiver decodeObjectForKey:@"keyValueString"]; // auto-released

[unarchiver finishDecoding];

[unarchiver release];

[data release];


** SQLite3

 object- relational mapping (ORM) is provided by Core Data

// open

sqlite3 *database;

int result = sqlite3_open("/path/to/database/file", &database);

// close

sqlite3_close(database);

// execution

char * errorMsg;

const char *createSQL = "CREATE TABLE IF NOT EXISTS PEOPLE

 (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIELD_DATA TEXT)";

int result = sqlite3_exec (database, createSQL, NULL, NULL, &errorMsg);

// retrieval

NSString *query = @"SELECT ID, FIELD_DATA FROM FIELDS ORDER BY ROW";

sqlite3_stmt *statement;

int result = sqlite3_prepare_v2( database, [query UTF8String],-1, &statement, nil);

while (sqlite3_step(statement) == SQLITE_ROW) {

    int rowNum = sqlite3_column_int(statement, 0);

    char *rowData = (char *)sqlite3_column_text(statement, 1);

    NSString *fieldValue = [[NSString alloc] initWithUTF8String:rowData];

    // Do something with the data here

    [fieldValue release];

}

sqlite3_finalize(statement);


Ch12. Drawing with Quartz and OpenGL


* Quartz 2D: painter's model on a virtual canvas with invisible pen (context)

* OpenGL ES: state machine, virtual window into its 3D world


** Quartz 2D **

Core Graphics’s API is C based.


// retrieves the current context

CGContextRef context = UIGraphicsGetCurrentContext();


CGPoint(x, y)

CGSize(width, height)

CGRect(CGPoint origin, CGSize size)


Color: (Red, Green, Blue) * alpha

[UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0f]


Draw images directly into a context:

CGImage or UIImage (ObjC alternative)


when an object instance is loaded from a nib, neither init: or initWithFrame: ever gets called. Instead, initWithCoder: is used.


setNeedsDisplay:  vs. setNeedsDisplayInRect:


We need to redraw not just the rectangle between firstTouch and lastTouch but any part of the screen encompassed by the current drag.


** OpenGLES **

http://www.khronos.org/opengles/


OpenGL ES doesn’t have sprites or images, per se; it has textures. draw a polygon, and then map a texture onto that polygon


[1] you draw in the context.

[2] once all your drawing is done, you render the context into the buffer.

[3] you present your render buffer, which is when the pixels actually get drawn onto the screen.


Ch13. Taps, Touches, and Gestures


160 pixels per inch


gesture is any sequence of events that happens from the time you touch the screen with one or more fingers until you lift your fingers off the screen.


iPhone only keeps track of tapswhen one finger is used.


The first responder is almost always a view or control and gets the first shot at responding to an event.


responder chain: view -> view's view controller -> view's parent view -> view's parent's view controller -> ...

If an object intercepts an event that it doesn’t handle, it needs to pass it along manually, by calling the same method on the next responder.


Every object in touches is a UITouch event that represents one finger touching the screen.

Every UITouch object knows its current position in the view, as well as its previous position in the view.


Ch14. Core Location


CLLocationManager *locationManager = [[CLLocationManager alloc] init];


Our delegate must conform to the CLLocationManagerDelegate protocol.


// self conforms to CLLocationManagerDelegate protocol

locationManager.delegate = self;

locationManager.desiredAccuracy = kCLLocationAccuracyBest;

locationManager.distanceFilter = 1000.0f;

// start continuously polling the location

[locationManager startUpdatingLocation];


The accuracy value is in meters, so if you specify a desiredAccuracy of 10, you’re telling Core Location that you want it to try to determine the current location within 10 meters, if possible.

Distance filters are also set in meters.


Ch15. Accelerometer

(+x: right, +y: up, +z: front)


Accelerometers give measurements in  g- forces (“g” for gravity), so a value of 1.0 returned by the accelerometer means that 1 g is sensed in a particular direction.


 // singleton

UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];

accelerometer.delegate = self;          // UIAccelerometerDelegate protocol

accelerometer.updateInterval =  1.0f/60.0f;


accelerometer:didAccelerate:           // delegate method

UIAcceleration object                      // passed object for acceleration data


** detect shaking (1.5g ~ 2g, max: 2.3g)

- (void)accelerometer:(UIAccelerometer *)accelerometer 

    didAccelerate:(UIAcceleration *)acceleration {

    

    if (fabsf(acceleration.x) > 2.0  

        || fabsf(acceleration.y) > 2.0 

        || fabsf(acceleration.z) > 2.0) {

        // Do something here...

    }

}


If you’re doing animation based on input from the accelerometer, you have to keep track of the time that passes between delegate method calls.


When using the accelerometer as a controller, you’ll need to poll at a considerably faster rate, usually between 30 and 60 updates per second.


Ch16. Camera and Photo Library

UIImagePickerController

1. create an instance of this class

2. specify a delegate

3. specify its image source

4. launch it modally


[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]


UIImagePickerController *picker = [[UIImagePickerController alloc] init];

picker.delegate = self;                // UIImagePickerControllerDelegate protocol

picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

[self presentModalViewController:picker animated:YES];

[picker release];


UIImagePickerController is a subclass of UINavigationController, we have to conform our class to both of these protocols.


Ch17. Application Localization

<2 or 3 language code (lower case)>_<2 letter country code (upper case)>.lproj


Full name localization project, such as French.lprj. exists to support legacy Mac OS X applications, and you should avoid it.


* resouce searching order

1. language_country matching resource

2. language matching resource

3. base language resource


* string files *

/* comments */ 

"First Name" = "First Name"; 

-----

NSString *myString = @"First Name";

NSString *myString = NSLocalizedString(@"First Name", 

    @"Used to ask the user his/her first name");


genstrings ./Classes/*.m

import (not copy) Localizable.strings as UTF-16 char. set file.



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

댓글을 달아 주세요

오브젝트C2010. 6. 24. 14:13
The Objective-C 2.0 Programming Language
Ch1. Objects, Classes, and Messaging

In Objective-C, it is valid to send a message to nil - it simply has no effect at runtime and returns nil.


A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message and a receiving object aren’t united until the program is running and the message is sent. Therefore, the exact method that’s invoked to respond to a message can only be determined at runtime, not when the code is compiled.


Objective-C provides a dot (.) operator that offers a compact and convenient syntax you can use as an alternative to square bracket notation ([]s) to invoke accessor methods.

Despite appearances to the contrary, the dot syntax therefore preserves encapsulation—you are not accessing an instance variable directly.


If you want to access a property of self using accessor methods, you must explicitly call out self


class object -> class instance

A class that doesn’t need to inherit any special behavior from another class should nevertheless be made a subclass of the NSObject class.

myRectangle = [[Rectangle alloc] init];

Every class object has at least one method (like alloc)that enables it to produce new objects, and every instance has at least one method (like init) that prepares it for use.


Unlike C++, there is no static class member variable, instead you should define static variable in the@implementation file.


class method vs. instance method?

The runtime system sends an initialize message to every class object before the class receives any other messages and after its superclass has received the initialize message.


When a class object receives a message that it can’t respond to with a class method, the runtime system determines whether there’s a root instance method that can respond.


The class name can stand for the class object only as a message receiver.

ex) [anObject isKindOfClass:[Rectangle class]]

It would have been illegal to simply use the name “Rectangle” as the argument.


class equality test

[objectA class] == [objectB class]


Ch2. Defining a Class

+ class method

- instance method

If a return or argument type isn’t explicitly declared, it’s assumed to be the default type for methods and messages — an id.


#import directive is identical to #include, except that it makes sure that the same file is never included more than once.


@class Rectangle, Circle;

The @class directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name.


** typical interface (.h file) **

#import "ItsSuperclass.h"

@interface ClassName : ItsSuperclass

{

    instance variable declarations

}

method declarations

@end


** typical implementation (.m file) **

@implementation ClassName : ItsSuperclass

{

    instance variable declarations

}

method definitions

@end


** simple implementation by importing header file **

#import "ClassName.h"

@implementation ClassName

method definitions

@end


By default, all unmarked instance variables are @protected. (private in C++ class, public in C++ struct)


self - class of the object that is sending message. If it is called in a inherited method, self is the class of the derived object.

super - class above the class where the method is defined.


Ch3. Allocating and Initializing Objects

Because an init... method might return an object other than the newly allocated receiver, or even return nil, it’s important that programs use the value returned by the initialization method.


** dangerous **

id anObject = [SomeClass alloc];

[anObject init];

[anObject someOtherMessage];

** safe **

id anObject = [[SomeClass alloc] init];

[anObject someOtherMessage];

-- or --

id anObject = [[SomeClass alloc] init];

if ( anObject )// check for nil is needed.

    [anObject someOtherMessage];

else

    ...


In general, if there is a problem during an initialization method, you should call [self release] and return nil.

You should only call [self release] at the point of failure. If you get nil back from an invocation of the super class’s initializer, you should not also callrelease.


You should typically not use exceptions to signify errors of initializer.


General Principle:The designated initializer in a class must,through a message to super, invoke the designated initializer in a superclass.


Ch4. Declared Properties

@interface MyClass : NSObject

{

    NSString *value;

}

@property(copy, readwrite) NSString *value;

@end

---

@implementation MyClass

@synthesize value;

@end

---

@synthesize age = yearsOld; // accessor: age, instance variable: yearsOld


When you synthesize a property, the compiler only creates any absent accessor methods.


attributes = (readwrite | readonly) | (assign | retain | copy) | (nonautomic) | (setter=) | (getter=)


You cannot specify the retain attribute for non-objecttypes.


informal decorator = (IBOutlet) | (__weak | __strong)


With @dynamic, you notify the compiler that you would provide the methods.


// assume using garbage collection

@implementation MyClass

@dynamic value;

- (NSString *)value {

    return value;

}

- (void)setValue:(NSString *)newValue {

    if (newValue != value) {

        value = [newValue copy];

    }

}

@end


You can re-declare a property in a subclass, but (with the exception of readonly vs. readwrite) you must repeat its attributes in whole in the subclasses.

If you declare a property in one classas readonly, you can redeclare it as readwrite in a class extension.

- a mutable subclass of an immutable class

- read only in public API, readwrite in private implentation file


the copy method returns an immutable version of the collection. You have to provide your own setter to set mutable object property.


@interface MyClass : NSObject {

    NSMutableArray *myArray;

}

@property (nonatomic, copy) NSMutableArray *myArray;

@end


@implementation MyClass

@synthesize myArray;

- (void)setMyArray:(NSMutableArray *)newArray {

    if (myArray != newArray) {

        [myArray release];

        myArray = [newArray mutableCopy];

    }

}

@end


You can look for all the property declarations in your header file and make sure that object properties not marked assign are released, and those marked assign are not released.


You should use invoke the accessor method on modern runtime.


- (void)dealloc {

    [self setProperty:nil];

    [super dealloc];

}


** property declaration meaning **

// assign

property = newValue;

// retain

if (property != newValue) {

    [property release];

    property = [newValue retain];

}

// copy

if (property != newValue) {

    [property release];

    property = [newValue copy];

}

// atomic

[_internal lock]; // lock using an object-level lock

id result = [[value retain] autorelease];

[_internal unlock];

return result;


Simply making all the properties in your class atomic does not mean that your class or more generally your object graph is “thread safe”.


The modern runtime supports instance variable synthesis whereas the legacy runtime does not.


Ch5. Categories and Extensions

A category allows you to add methods to an existing class—even to one to which you do not have the source.

Class extensions are similar, but allow additional required API to be declared for a class in locations other than within the primary class @interface block.


Category methods can do anything that methods defined in the class proper can do. At runtime, there’s no difference. The methods the category adds to the class are inherited by all the class’s subclasses, just like other methods.


#import "ClassName.h"

@interface ClassName ( CategoryName )

// method declarations

@end


A category implementation (in a file named ClassName+CategoryName.m) might therefore look like this:


#import "ClassName+CategoryName.h"

@implementation ClassName ( CategoryName )

// method definitions

@end


Normally, class objects can perform only class methods. But instance methods defined in the root class are a special case.


Class extensions are like “anonymous” categories, except that the methods they declare must be implemented in the main @implementation block for the corresponding class.


Ch6. Protocols

A protocol is simply a list of method declarations, unattached to a class definition.


@protocol MyXMLSupport

- initFromXMLRepresentation:(NSXMLElement *)XMLElement;

@property (nonatomic, readonly) (NSXMLElement *)XMLRepresentation;

@end


Unlike class names, protocol names don’t have global visibility. They live in their own namespace.


The default is @required.

@protocol MyProtocol

- (void)requiredMethod;

@optional

- (void)anOptionalMethod;

- (void)anotherOptionalMethod;

@required

- (void)anotherRequiredMethod;

@end


** On Mac OS X v10.5, protocols may not include optional declared properties.


** sender **

Source code can refer to a Protocol object using the @protocol() directive.

Protocol *myXMLSupportProtocol = @protocol(MyXMLSupport);


** receiver **

Adopting a formal protocol:

@interface ClassName : ItsSuperclass < protocol list >

Categories adopt protocols in much the same way:

@interface ClassName ( CategoryName ) < protocol list >


A class is said to conform to a formal protocol if it adopts the protocol or inherits from another class that adopts it.

if (![receiver conformsToProtocol:@protocol(MyXMLSupport)]) {...


conformsToProtocol: is both class and instance method.


Protocols can’t be used to type class objects. Only instances can be statically typed to a protocol, just as only instances can be statically typed to a class.


One protocol can incorporate other protocols:

@protocol ProtocolName < protocol list >


A class can conform to a protocol without formally adopting it simply by implementing the methods declared in the protocol.


circular dependency between protocols (x) -> forward reference (o)

@protocol B;

@protocol A

- foo:(id <B>) anObject;

@end


Ch7.Fast Enumeration

for ( Type newVariable in expression ) { statements }

: expression should adopt NSFastEnumeration protocol.


Since mutation of the object during iteration is forbidden, you can perform multiple enumerations concurrently.


Ch8. Enabling Static Behavior

Static typing also doesn’t affect how the object is treated at runtime. Messages sent to statically typed objects are dynamically bound, just as objects typed id are.Static typing allows for compile-time type checking.


Methods in different classes that have the same selector must also share the same return and argument types.


Ch9. Selectors

Compiled selectors are assigned to a special type, SEL.

The @selector() directive lets you refer to the compiled selector.

SEL setWidthHeight;

setWidthHeight = @selector(setWidth:height:);


To convert a character string to a selector at runtime:

setWidthHeight = NSSelectorFromString(aBuffer);


Conversion in the opposite direction is also possible:

NSString *method;

method = NSStringFromSelector(setWidthHeight);


Compiled selectors identify method names, not method implementations. It lets you send the same message to receivers belonging to different classes.


Except for messages sent to statically typed receivers, dynamic binding requires all implementations of identically named methods to have the same return type and the same argument types.


[friend performSelector:@selector(gossipAbout:)withObject:aNeighbor];

is equivalent to:

[friend gossipAbout:aNeighbor];


The receiver and message can vary at runtime:

id      helper = getTheReceiver();

SEL    request = getTheSelector();

[helper performSelector:request];


Ch10. Exception Handling

Just like the C++ / Java language.

@try {

    ...

}

@catch (CustomException *ce) {// 1

    ...

}

@catch (NSException *ne) {// 2

    // Perform processing necessary at this level.

    ...

}

@catch (id ue) {

    ...

}

@finally {// 3

    // Perform processing necessary whether an exception occurredor not.

    ...

}


** Throwing exceptions **

NSException *exception = [NSException exceptionWithName:@"HotTeaException"reason:@"The tea is too hot"userInfo:nil];

@throw exception;


Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors.

Inside a @catch()block, you can re-throw the caught exception using the @throw directive without an argument.


Ch11. Threading

To turn on support for thread sync. and exception handling, use the -fobjc-exceptions switch. Itrenders the application runnable only in Mac OS X v10.3 and later.


The @synchronized() directive takes as its only argument any Objective-C object, including self.

- (void)criticalMethod

{

    @synchronized(self) {

        // Critical code.

        ...

    }

}

When code in an @synchronized() block throws an exception, the Objective-C runtime catches the exception, releases the semaphore (so that the protected code can be executed by other threads), and re-throws the exception to the next exception handler.


Ch12. Remote Messaging

A remote receiver is typically anonymous.an object that’s designated to receive remote messages advertises its inter face in a formal protocol.


// asynchronous

- (oneway void)waltzAtWill;         

// information is being passed in a message 

- setTune:(in struct tune *)aSong;

// an argument is being used to return information by reference

- getTune:(out struct tune *)theSong;

// an argument is used both to provide information and to get  information back

- adjustTune:(inout struct tune *)aSong;

// composite value, not a simple pointer

- getTuneTitle:(out char **)theTitle;

// send an object, not a proxy

- danceWith:(bycopy id)aClone;

// objects passed or returned by reference

byref


Ch13. C++ with ObjC

You can include pointers to Objective-C objects as data members of C++ classes, and you can include pointers to C++ objects as instance variables of Objective-C classes.

Xcode requires that file names have a “.mm” extension for the Objective-C++ extensions to be enabled by the compiler.


C++ classes defined within an Objective-C interface are globally-scoped, not nested within the Objective-C class.

C++ classes that have virtual member function cannot serve as an ObjC instance variable.


** preprocessor constants **

__cplusplus

__OBJC__


Objective-C++ does not allow you to inherit C++ classes from Objective-C objects, nor does it allow you to inherit Objective-C classes from C++ objects. The layout of Objective-C and C++ objects in memory is mutually incompatible.


Objective-C does not have a notion of nested namespaces. You cannot declare Objective-C classes within C++ namespaces, nor can you declare namespaces within Objective-C classes.


Objective-C classes, protocols, and categories cannot be declared inside a C++ template, nor can a C++ template be declared inside the scope of an Objective-C interface, protocol, or category.


However, Objective-C classes may serve as C++ template parameters. C++ template parameters can also be used as receivers or parameters (though not as selectors) in Objective-C message expressions.


You cannot use Objective-C syntax to call a C++ object, you cannot add constructors or destructors to an Objective-C object.


An exception thrown in Objective-C code cannot be caught in C++ code and, conversely, an exception thrown in C++ code cannot be caught in Objective-C code.



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

'오브젝트C' 카테고리의 다른 글

Object-C : Declared Properties 에 대한 깔끔한 정리  (0) 2010.08.12
Hello iPhone - 1  (0) 2010.08.11
The Objective-C 2.0 Programming Language  (0) 2010.06.24
Objective-C  (0) 2010.06.22
Objective-C의 기본 문법  (0) 2010.06.22
Objective-C의 특징  (0) 2010.06.22
Posted by 오늘마감

댓글을 달아 주세요

아이폰어플개발정보2010. 6. 24. 14:13
The iPhone Developers Cookbook
Cookbook is loaded with heaps of tricks. These are some notes from the book.

* Origin

- Quartz: bottom left

- UIViews: top left


* screenshotting (non-public API)

@interface UIApplication (Extended)

-(void) _writeApplicationSnapshot;

@end

[[UIApplication sharedApplication] _writeApplicationSnapshot];


* Transition

- CATransition class: applied to the view's default layer

- UIView's built-in transition animation


* Audio service interfering with iPod audio

- Celestial: do interfere

- System Audio service: doesn't interfere


* MPMoviePlayerController plays by its own rules.You do not push it onto a navigation stack.You do not invoke it modally. Instead, you create it and tell it to play.

: Supported file types include MOV, MP4, MPV, M4V, and 3GP, as well as MP3, AIFF, M4A.


* Reading in Text Data

NSString *path = [[NSBundle defaultBundle] pathForResource:@"myText" ofType:@"txt"]; NSString *fileText = [NSString stringWithContentsOfFile:path encoding: NSUTF8StringEncoding error:nil];


* Writing out Text Data

NSError *error; [myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];


* Reading in plist file

NSDictionary *plist = [NSMutableDictionary dictionaryWithContentsOfFile:PLISTPATH];

if (plist) textView.text = [plist description]; else textView.text = @"Could not read property list from file";


* Core location

1. GPS or SkyHook WiFi

2. Google Maps cell tower location

3. SkyHook Internet provider location


Gus Mueller’s FMDB Cocoa wrappers: http://gusmueller.com/x/fmdb.zip

Send a simple SQLite call as an NSString query ([db executeQuery:@"select * from call"])



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

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

iPhone Human Interface Guidelines  (0) 2010.06.24
iPhone Games Projects  (0) 2010.06.24
The iPhone Developers Cookbook  (0) 2010.06.24
Memory Management Programming Guide for Cocoa  (0) 2010.06.24
iPhone Development Guide  (0) 2010.06.24
Quartz2D로 한글 그리기..  (0) 2010.06.24
Posted by 오늘마감

댓글을 달아 주세요