출처 - http://shapeace.tistory.com/27

 

 

iPhone Programming for Dummy

1. iPhone SDK 설치


1.1. 시작하기

iPhone SDK 는 Apple 사에서 무료로 배포하고 있는 개발 도구로서, 누구든지 애플 개발 사이트에 등록하면 다운로드 받을 수 있다. 여기에는 Gcc 를 기반으로 한 Xcode 개발 환경과, Mac 에서 모든 것을 테스트 할 수 있는 에뮬레이터, 그리고 실제 장비에서 실행시키면서 수행 성능을 튜닝할 수 있는 성능 측정 프로그램 등 실제 개발 업무에 필요한 모든 것들이 포함되어 있다.

설치하기전, 먼저 다음과 같은 사항이 준비되었는지 확인하자.

  • Intel CPU 기반의 Mac Computer
기본적으로 iPhone SDK 는 Intel 기반의 Mac 에서만 사용할 수 있다. PPC 기반의 Mac 에서 SDK 를 설치한다면,
iPhone 과 관련된 사항은 설치되지 않는다. 그런데, PPC 기반의 Mac 에서도 전혀 불가능 한 것은 아니다.
이것에 대해서는 1.3. PPC 에서 설치하기 부분에서 다시 다루도록 하겠다.

  • 10.5.3 이상의 Mac OS X
이 버전 이하의 Mac OS 에서는 Xcode 가 설치되지 않게 되어 있다. 처음에는 그렇지 않았는데,
SDK Beta 6 부터에서 이런 제약이 생겼다.

  • C 프로그래밍 언어에 대한 기본 이해
정확하게는 Objective-C 언어에 대한 이해가 있어야 한다. Mac 에서 사용하는 Xcode 개발 환경은 기본적으로 Objective-C 언어에 기반하고 있으며, 그 역사는 NeXT Step 시스템으로 까지 거슬러 올라간다. 문제는 Objective-C 언어에 대해 아는 사람이 그리 많지 않다는 것이지만, 다행이도 Objective-C 언어는 C++ 만큼 어려운 언어는 아니다. 이 문서에서는 Objective-C 언어 자체에 대해 깊이 다루는 것은 피하도록 할 것이다. 단, C 언어 자체에 대한 이해조차 없다면 iPhone SDK 를 사용한 개발은 잠시 접어두고 C 언어 공부를 하고 오는 것을 권한다. 이 문서에서도 독자가 C 언어에 익숙하다는 것을 전제로 한다.


1.2. SDK 설치하기

Developer Connection 에 등록된 사람이라면 http://developer.apple.com/iphone/index.action 에서 SDK 를 다운로드 받을 수 있다.

약 1.2 GB 의 dmg 파일이 다운로드된다. 다 받았다면, 당연히 다운받은 dmg 파일을 마운트한다.
마운트하면 다음과 같은 내용이 보이는 디스크 이미지가 나타날 것이다.

두 번째 보이는 iPhone SDK 패키지 파일을 더블 클릭하여 설치를 시작하면 된다. Packages 폴더의 내용은 특별히 볼 필요 없다. 설치 과정에서 이 폴더에 있는 내용들이 로컬 디스크에 설치될 것이다. 단, PPC 환경에서 SDK 를 설치하는 사용자는 나중에 이 폴더를 열어볼 일이 생긴다.

설치 과정은 간단하다. 디스크 볼륨을 선택해주고, 별다른 설정 변경 없이 기본값으로 선택해서 진행하면 모든 것이 OK 이다.
설치 프로그램을 몇 단계 진행한 후 시스템 관리자 암호 창이 뜨고, 여기에 암호를 입력하면 다음 그림과 같은 화면이 나타나면서 설치가 진행된다. 십분 이상을 기다리면 설치가 완료된다.



설치 시간이 생각보다 길다고 불평하는 사람이 있을 지도 모르겠다. 하지만 이것은 단지 iPhone 응용 프로그램만을 만들기 위한 환경이 아니라, Java를 포함해서 Mac OS 용 프로그램을 만들 수 있는 모든 개발 환경이 포함되어 있는 것이다.

소프트웨어 설치가 끝나면, /Developer/Application 아래에 몇 가지 개발 프로그램들이 설치되어 있는 것을 확인할 수 있다.

Intel CPU 기반의 Mac 을 사용하는 사람이라면, 이제 기본적인 준비는 끝마친 셈이다.


1.3. PPC 에서 설치하기

이상의 과정을 모두 거치더라도 불쌍하게도 PowerPC 기반의 Mac을 사용하는 경우에는 iPhone 응용 프로그램 개발을 할 수 없다. 단지 Mac 데스크탑용 프로그램을 개발할 수 있는 Xcode 환경이 설치되어 있을 뿐이다. Apple 에서도 공식적으로는 PPC 기반의 Mac 에서 iPhone 응용 프로그램을 개발할 수 없다고 선언하고 있다.

그러나 방법은 있다. 다음의 과정을 통해서 G4, G5 Mac 에서도 iPhone 프로그램 개발을 해볼 수 있다. 단, 미리 말하지만 몇가지 사용할 수 없는 기능들이 있다고 하는데, 아직 정확하게 파악하지는 못했다. 그러나 기본적인 거의 모든 기능들을 문제없이 사용할 수 있다.

먼저, 설치하기 위해 마운트했던 디스크 이미지로 돌아가보자.
여기에는 앞서 말했듯이 packages 라는 이름의 폴더가 있다. 여기로 들어가 보면 각종 설치 패키지들이 보일 것이다.

SDK 설치 과정에서 자동으로 설치되었던 각종 패키지들이 여기에 있다. 그런데, 설치하면서 보았을 지도 모르겠지만, PPC 사용자들은 iPhone 관련 항목들이 설치되지 않았다. 선택 항목이 비활성화 되어서 임의로 선택할 수도 없었을 것이다.

이 제 할 일은, 여기서 iPhone 으로 시작하는 이름을 가진 5개 패키지를 하나씩 일일이 수동으로 설치하는 것이다. 설치 과정에서 설치할 폴더의 위치를 변경할 수 있는 단계도 나오는데, 일단 5개 모두 기본으로 설치하도록 클릭해서 넘어가도록 한다.

이런 식의 화면을 보면서 일일이 설치해야 한다...

모두 설치했다면, Finder 로 하드디스크의 루트(/) 위치를 살펴보자. 여기에 'Platforms' 라는 폴더가 생겼을 것이다.그리고 그 아래에는 두 개의 폴더가 있는데, 이 두 개의 폴더를 전부 /Developer/Platforms 아래로 이동한다.
겹 치는 폴더와 파일이 많기 때문에, 중복 확인 창이 뜨면 '대치' 하도록 해야 하는데, 여기서 기존 위치의 폴더 속성 문제로 한번에 파일 이동이 되지 않을 것이다. 문제가 되는 부분들을 하나씩 찾아서 하면 큰 문제 없이 모든 파일을 옮길 수 있을 것이다.

이제 힘든 대부분의 과정을 거쳤다.
마지막 단계가 하나 있는데, 일단 아래 경로를 찾아가서 파일들을 확인한다.

/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Specification

꽤나 길다. 최종 목적지에 다다르면 3개의 파일이 있을 것이다.
여기서 iPhone Simulator Architectures.xcspec 이라는 이름의 파일을 텍스트 편집기로 열자.
이 파일의 내용은 아래와 같다. 이것은 iPhone 시뮬레이터용으로 컴파일러가 코드를 생성할 때 어떤 타겟으로 만들 수 있는지에 대한 설정값이다.

 
/**
    iPhone Simulator Architectures.xcspec
   
    Copyright (c) 2008 Apple Inc.  All rights reserved.

    Architecture specifications in the iPhone Simulator platform.
*/
(
    // 32-Bit
    {   Type = Architecture;
        Identifier = Standard;
        Name = "Standard (iPhone Simulator: i386)";
        Description = "32-bit iPhone Simulator architectures";
        ListInEnum = YES;
        SortNumber = 1;
        RealArchitectures = ( i386 );
        ArchitectureSetting = "ARCHS_STANDARD_32_BIT";
    },

    // Old-style Debug
    {    Type = Architecture;
        Identifier = Native;
        Name = "Native Architecture of Build Machine";
        Description = "32-bit for build machine";
        ListInEnum = YES;
        SortNumber = 101;
        ArchitectureSetting = "NATIVE_ARCH";
    },

    // Intel
    {   Type = Architecture;
        Identifier = i386;
        Name = "Intel";
        Description = "32-bit Intel";
        PerArchBuildSettingName = "Intel";
        ByteOrder = little;
        ListInEnum = NO;
        SortNumber = 105;
    },
)

원본 파일은 만약을 위해 각자 편한 방식으로 백업해 두길 권한다.
그리고 이 파일의 내용을 다음과 같이 수정한 후 저장하자.

 /**
    iPhone Simulator Architectures.xcspec
   
    Copyright (c) 2008 Apple Inc.  All rights reserved.

    Architecture specifications in the iPhone Simulator platform.
*/
(
    // 32-Bit
    {   Type = Architecture;
        Identifier = Standard;
        Name = "Standard (iPhone Simulator: ppc)";
        Description = "32-bit iPhone Simulator architectures";
        ListInEnum = YES;
        SortNumber = 1;
        RealArchitectures = ( ppc );
        ArchitectureSetting = "ARCHS_STANDARD_32_BIT";
    },

    // Old-style Debug
    {    Type = Architecture;
        Identifier = Native;
        Name = "Native Architecture of Build Machine";
        Description = "32-bit for build machine";
        ListInEnum = YES;
        SortNumber = 101;
        ArchitectureSetting = "NATIVE_ARCH";
    },

    // G5 32-bit
    {   Type = Architecture;
        Identifier = ppc;
        Name = "PowerPC G5 32-bit";
        Description = "32-bit PowerPC for G5 processor";
        ByteOrder = big;
        ListInEnum = NO;
        SortNumber = 203;
    }
)

이 작업을 하지 않으면 코드를 작성하더라도 에뮬레이터를 사용할 수 없다. 이렇게 힘든 과정을 모두 통과하였다면 PPC 사용자들도 이제 iPhone SDK 를 사용할 자격을 비로소 얻게 된다.


자, 이제 모두 출발선에 섰다. 계속 달려갈 결심을 하는 일 만 남은 셈이다.
Intel 이건 PPC 건, 이제 구분하지 말고 Xcode 의 얼굴을 구경해보자. Xcode 가 어디있냐고? 보나마나 /Developer 아래 어딘가에 있겠지만 알게 뭔가. 그냥 Spotlight 에서 Xcode 라고 타이핑 한 후 Enter 키를 눌러보면 되지. 그리고 나서 Xcode 는 그냥 Dock 에 등록해 버리자.



환 영합니다. Dummy 여러분.

 



출처 : http://blog.naver.com/PostView.nhn?blogId=seogi1004&logNo=110086946825
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
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 오늘마감

댓글을 달아 주세요

아이폰어플개발정보2010. 6. 24. 14:13
Memory Management Programming Guide for Cocoa

- garbage collected environment: Mac OS X 10.5+

- reference counted environment: iPhone OS


Object ownership policy: responsibility for disposal


** policy **

- You own any object you create (alloc, new, copy)

- If you own an object, you are responsible for relinquishing ownership when you have finished with it.

- If you do not own an object (convenience constructor), you must not release it.


// typical good example

Thingamajig *thingamajig = [[Thingamajig alloc] init];

// ...

NSArray *sprockets = [thingamajig sprockets];

// ...

[thingamajig release];


// typical wrong example

// 1 - convenience method

Thingamajig *thingamajig = [Thingamajig thingamajig];

[thingamajig release]; // wrong


// 2 - function loses the chance to release

+ (Thingamajig *)thingamajig {

    id newThingamajig = [[Thingamajig alloc] init];

    return newThingamajig;

}


// 3 - no owner, disposed before returned

+ (Thingamajig *)thingamajig {

    id newThingamajig = [[Thingamajig alloc] init];

    [newThingamajig release];

    return newThingamajig; // newThingamajig is invalid here

}


autorelease - you declare that you don't want to own the object beyond the scope in which you sent autorelease.


– (NSArray *)sprockets {

    NSArray *array;

    array = [[NSArray alloc] initWithObjects:mainSprocket,

                               auxiliarySprocket, nil];

    return [array autorelease];

}


strong reference: pointer which retaining the object

weak reference: pointer that doesn't (usually to avoid mutual retaining each other) ex) table data sources,outlineview items,notification observers,and miscellaneous targets and delegates

** holder of weak reference SHOULD be notified when the objected is deallocated. **


** Don't piggy-back resource management on top of dealloc.

You should typically not manage scarce resources such as file descriptors,network connections,and buffers / caches in a dealloc method.Invocation of dealloc might be delayedor side stepped.


When you add an object to a collection such as an array,dictionary,or set,the collection takes ownership ofit.


** autorelease pools **

Anautorelease pool is an instance of NSAutoreleasePool that “contains” other objects that have receivedan autorelease message;when the autorelease poolis deallocated it sends a release message to eachof those objects. An object can be put into an autorelease pool several times, and receives a release messagefor each time it was put into the pool.


If you send an autorelease message when a poolis not available,Cocoa logs a suitable error message.


Autorelease pools are arranged in a stack,although they are commonly referred to as being "nested." When an object is sent an autorelease message, it is added to the current top mostpoolfor the current thread.


If you spawn a secondary thread,you must create your own autorelease poolas soon as the thread begins executing.


Anyautoreleasedobjectscreatedduringthelifetimeofthetaskarenotdisposedofuntilthetaskcompletes.


Ifyoureleaseanautoreleasepoolthatisnotthetopofthestack,thiscausesall(unreleased)autorelease poolsaboveitonthestacktobereleased,alongwithalltheirobjects.


in garbaged collected environment

- release: no-op

- drain of autorelease pool: triggers garbage collection (if the last collection > current threshold)


Youshouldusedrainratherthanreleaseto disposeofanautoreleasepool.


NSCopyObjectcreatesanexactshallowcopyofanobjectbycopyinginstancevariablevaluesbutnotthedatatheypointto.


Zonesarepage-alignedareasofmemorythatholdtheobjectsanddataallocatedbyanapplication. Thesystemassignseachapplicationa“default”zoneinitiallyandapplicationscancreateadditionalzoneslater.



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

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

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
맥에서 화면 녹화하기  (0) 2010.06.24
Posted by 오늘마감

댓글을 달아 주세요