u Associative References

n  용도

기존의 클래스오브젝트의 인스턴스변수를 의사적으로 추가

Associative ReferencesMac OS X v10.6이후 에서만 사용 가능

 

n  Adding Storage Outside a Class Definition

클래스 선언을 변경하지않고 오브젝트에 스토리지를 추가 가능

클래스 소스코드에 접근 불가한 경우에 사용 가능

 

n  Creating Associations

런타임 함수 objc_setAssociatedObject를 사용

objc_setAssociatedObject 4개의 인수가 필요 (소스오브젝트, , , 폴리시정수)

(void포인터) : static변수를 사용하는 것이 일반적

폴리시정수 : 관련오브젝트를 대입할것인지, 유지할것인지, 복사할것인지를 지정

static char overviewKey;

NSArray *array = [[NSArray alloc] initWithObjects:@"One", @"Two", @"Three", nil];

NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];

objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);

[overview release];

// (1) overview valid

[array release];

// (2) overview invalid

 

 

n  관련 오브젝트의 취득

NSString *associatedObject = (NSString *)

objc_getAssociatedObject(array,&overviewKey);

 

n  Breaking Associations

objc_setAssociatedObject(array, &overviewKey, nil,

OBJC_ASSOCIATION_ASSIGN);

 

 

 

Posted by 김반장78
,

u 카테고리와 확장

n  의미

기본은 수직상속만 가능, 메소드를 추가해야할 경우 수직상속

카테고리를 사용함으로서 메소드의 수평적 상속이 가능

소스를 가지고 있는 않은 클래스에도 추가할 수 있음

카테고리를 사용해서 클래스의 implementation을 여러 파일로 쪼갤 수 있음

선언과 구현이 분리되어 있고, 클래스에 종속되어 있지 않음

 

n  Adding Methods to Classes

카테고리가 클래스에 추가한 method들은 클래스의 subclass 의해 상속

#import "ClassName.h"
 
@interface ClassName ( CategoryName )
// method declarations

@end

             -특징

               파일명이 ClassName+CategoryName.m으로 됨

#import "ClassName+CategoryName.h"
 
@implementation ClassName ( CategoryName )
// method definitions

@end

               오직 method 추가할 있음

               클래스 scope 모든 instance variables(@private조차도) 카테고리의 scope이므로

모두 접근이 가능

무한정 작성 가능

 

n  How you Use Categories

다른 implementation 의해 정의된 클래스들을 확장할

Cocoa frameworks 정의된 클래스들에 method들을 추가할

             subclass 대안으로 쓰려고

             클래스의 implementation 개의 소스 화일로 분배하려

             informal protocol 선언하기 위해

 

n  Categories of the Root Class

super 대한 message 가능

class object 루트 클래스에 정의된 instance method 수행할 있다

             보통 class object class method 수행하지만 루트 클래스에 정의된 instance method

특별한 경우이다.

카테고리로 추가한 instance method가 루트 클래스에서 수행되므로 예측이 불가능하게 되어 루트

클래스에 카테고리 사용은 바람직하지 못하다.

Posted by 김반장78
,

u 프로퍼티

n         프로퍼티 선언

Property 사용하기 위해서 일반적으로 @property 지시자와 @synthesize 지시자를 함께 사용

@property 지시자는 클래스의 @interface 내부에 선언하며 다음과 같은 형식으로 선언

@interface MyClass : NSObject
{
    float value;
}
@property float value;

@end

 

@property float value

위의 선언은 다음과 같이 두가지 메서드를 선언한것과 같은 기능

- (float)value;

- (void)setValue:(float)newValue;

 

n         @synthesize

구현부안에 getter, setter를 지정안했을경우@synthesize를 통해 컴파일러에게 작성을 지시함

- 주의

  @synthesize를 사용안할 경우 직접 구현부에 getter, setter를 작성해야 컴파일 가능하나

  문제가 발생할 여지가 있으므로@synthesize사용을 권장

 

n         @property 지시자의 attributes

- getter=gettername

기본적으로 Property getter 메서드 명은 Property 자신의 이름과 동일 ( : Property foo일 경우 foo) 하지만 이 기본 설정을 내가 원하는 메서드명으로 변경 할 수 있습니다.

- setter=settername

Property setter 메서드 명은 setPropertyName: 입니다. ( : Property foo일 경우 setFoo:)

역시나 이 기본 설정을 내가 원하는 메서드명으로 변경 할 수 있습니다.

- readwrite (DEFAULT)

Property의 값을 읽고 쓸 수 있다는 것입니다. 이 설정은 기본 설정입니다.

- readonly

Property의 값을 단지 읽기만 할수 있다고 정의하는 속성입니다.

이 속성은 @implementation 블럭 안에서 오로지  getter 메서드만 필요할 경우에 사용합니다.

@synthesize 지시자를 사용하였을 경우에는 역시나 getter 메서드의 역할만을 하게 됩니다.

값을 대입 하려고 할 경우 에러를 출력하게 됩니다.

- assign (DEFAULT)

단순하게 값을 대입합니다. 기본설정입니다.

이전에 어떤 객체를 가리키고 있던 Property라면 이로 인해 해당 객체는 미아가 되어 메모리릭의 주범이 될 수 있습니다.

가비지콜렉터를 사용하지 않는다면 사용을 피해야 합니다.

- retain

이 것은 assign과 비슷하지만 조금 다릅니다.

이전에 가리키고 있던 객체가 있다면 해당 객체를 Release하여 메모리에서 제거 합니다.

- copy

객체를 바로 대입하지 않고 해당 객체의 복사 메서드를 Invoke호출합니다.

그리하여 다른 메모리 영역에 복사본을 만든 다음 그것을 반환하게 됩니다.

이전에 가리키고 있던 값은 Release 시킵니다.

- nonatomic

이 속성은 접근자 메서드가 Atomic 하지 않게 동작하게 합니다.

기본적으로 접근자는 Atomic하게 동작합니다.

Atomic 이라는 말은 멀티스레드 등으로 구성된 프로그램이 특정 접근자 메서드를 호출할때 서로 충돌이 나지 않도록 객체 레벨에서 Lock을 걸고 Property에 접근하게 됩니다.

이런 접근이 필요없다면 이 속성을 사용하여 Non-Atomic하게 동작하도록 만들어 주시는 것이 좋습니다.

- dealloc

객체가 제거 될때 소멸자로 dealloc 호출되는데 Property들이 자동으로 소거되지 않아

명시적으로 제거해 주셔야 합니다.

- (void)dealloc {
    [property release];
    [super dealloc];

}

 

n         재선언

서브클래스에서 슈퍼클래스의 프로퍼티의 재선언 가능

속성 선언을 다시 해줘야함

 

n         Markup and Deprecation

@property CGFloat x

AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;

@property CGFloat y __attribute__((...));

 

 

 

 

Posted by 김반장78
,

u 프로토콜

n         정의

Protocols는 클래스 정의와 관련 없는 mothod선언 목록.

Protocols는 정의되어 있지 않은 객체에 메시지를 전달하고자 할 때 사용 가능

 

n         사용 범위

- 다른 사람들이 구현해야 할 mothod를 선언할 때

- 클래스는 숨긴 상태에서 object interface을 선어할 때

- 계층적으로 관련없는 클래스 간에 유사성을 가지게 할 때

 

n         Declaring Interfaces for Others to Implement

프로토콜로 선언된 메소드를 사용하려면, 프로토콜을 adopt(클래스가 프로토콜의 모든 메소드를 구현한다는 의미)하고, 그 메소드들을 구현.

- (void)mouseDown:(NSEvent *)theEvent;

- (void)mouseDragged:(NSEvent *)theEvent;

- (void)mouseUp:(NSEvent *)theEvent;

 

n         Methods for Others to Implement

- setAssistant:anObject

{

    assistant = anObject;

}

 

n         Declaring Interfaces for Anonymous Objects

id formatter = [receiver formattingService];

 

n         Non-Hierarchical Similarities

- (NSXMLElement *)XMLRepresentation;

- initFromXMLRepresentation:(NSXMLElement *)xmlString;

 

n         Formal Protocols (선언 방법)

@protocol 지시자를 사용

@protocol ProtocolName

method declarations

@end

 

n         XML을 이용한 protocol 표현이 가능

@protocol MyXMLSupport

- initFromXMLRepresentation:(NSXMLElement *)XMLElement;

- (NSXMLElement *)XMLRepresentation;

@end

 

n         주의점

- protocol은 클래스랑 연관지어 쓰는 것으로 단독으로 사용되지 않는다.

  따라서, protocol 이름은 자체의 namespace안에만 있게 되어 global하게 접근할 수 없다.

- protocol을 사용하려면 class가 그 protocol adopt해야 한다.

- protocol adopt할 클래스에서는 protocol이 선언된 헤더파일을 import 해야 한다.

 

n         Informal Protocols(Category 선언 내에 method를 선언한 것)

@interface NSObject ( MyXMLSupport )

- initFromXMLRepresentation:(NSXMLElement *)XMLElement;

- (NSXMLElement *)XMLRepresentation;

@end

              특징

              - informal protocol category와 선언방식은 똑같다.

차이점은 Catogory는 구현을 따로 카테고리로 만들어서 해야 하는 반면,

informal protocol은 구현을 클래스의method로 해 준다

 

n         Protocol Objects

런타임시 클래스는 class object method selector formal protocol protocol class

protocol object @protocol(protocol_name)지시자로 참조할 수 있다.

Protocol *myXMLSupportProtocol = @protocol(MyXMLSupport);

 

n         Adoption a Protocol(adopt는 클래스가 protocol의 모든 mothod를 구현한다는 의미)

@interface ClassName : ItsSuperclass < protocol list >

@interface ClassName ( CategoryName ) < protocol list >

@interface Formatter : NSObject < Formatting, Prettifying >

 

n         Conforming to a Protocol

-클래스가 protocol adopt하고 있는지 알아보기 위해 conformsToProtocol:메시지를 object에 보낸다.

-respondsToSelector:는 한 method이 구현되어 있는지를 알려준다.

-isKindOfClass:는 클래스가 상속 계층구조안에 속하는지 여부를 알려준다.

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

    // Object does not conform to MyXMLSupport protocol

    // If you are expecting receiver to implement methods declared in the

    //  MyXMLSupport protocol, this is probably an error

}

 

n         Type Checking

protocol 타입선언 방법은 “type_name <protocol_name> 변수형태이다.

- (id <Formatting>)formattingService;

id <MyXMLSupport> anObject;

 

Formatter *anObject;

id <Formatting> anObject;
Formatter <Formatting> *anObject;

 

n         Protocols Within Protocols

@protocol ProtocolName < protocol list >

@protocol Paging < Formatting >

id <Paging> someObject;

 

if ( [anotherObject conformsToProtocol:@protocol(Paging)] )

 

n         상호참조 문제 해결

// A 선언

#import "B.h"

 

@protocol A

- foo:(id <B>)anObject;

@end

 

// B 선언

#import "A.h"

 

@protocol B

- bar:(id <A>)anObject;

@end

 

// A, B protocol이 상호 참조

@protocol B;

 

@protocol A

- foo:(id <B>)anObject;

@end

 

 

 


Posted by 김반장78
,

u 오브젝트의 메모리 할당과 초기화

n         객체생성시 요구사항

동적으로 새로운 객체를 메모리에 할당

새롭게 메모리에 할당된 객체에 적절한 값들로 초기화

작성예

id anObject = [SomeClass alloc];

[anObject init];

[anObject someOtherMessage];

간략화

id anObject = [[SomeClass alloc] init];

[anObject someOtherMessage];

반환값 체크

id anObject = [[SomeClass alloc] init];

if ( anObject )

[anObject someOtherMessage];

else

...

 

n         NSObject alloc, allocWithZone

NSObject는 모든 클래스가 상속받게되는 최상위 클래스 (자바의 Object클래스)

생성한 클래스와 클래스내의 인스턴스 변수들을 위한 메모리 공간 확보

확보한 메모리공간을 생성한 인스턴스변수가 가르키도록 지시(Pointer)

모든 인스턴스 변수들의 값을 0으로 세팅

 

n         초기화 메소드 구현

초기화 인스턴스 메소드의 명칭은 init로 시작

인자가 없는 초기화 메소드는 init:

인자가 있는 초기화 메소드는 initMethodName:

 

n         초기화 메소드 작성예

- 인자가 없는 경우

- (id)init {

self = [super init];

if (self) {

creationDate = [[NSDate alloc] init];

}

return self;

}

 

 

- 인자가 있는 경우

 

- (id)initWithImage:(NSImage *)anImage {

NSSize size = anImage.size;

NSRect frame = NSMakeRect(0.0, 0.0, size.width, size.height);

self = [super initWithFrame:frame];

If (self) {

image = [anImage retain];

}

return self;

}

 

n         메모리확보와 초기화의 결합

convenience constructors를 사용함으로서 메모리 자동해제(autorelease)를 적용

자동해제의 경우 직접해제를 할경우 크래시 발생

Posted by 김반장78
,

 

u 클래스 정의

n         Interface : 한 클래스의 메소드와 인스턴스 변수를 선언하고, 어느 수퍼클래스로부터 상속을 받는지를 기입

헤더 파일인 *.h 파일에 정의

 

n         Implementation : 실지로 클래스를 정의하는 부분

구현 파일인 *.m에 구현

 

n         해더 파일과 구현부를 나누는 이유

외부에서 볼때 구현부를 독립해 접근 불가능

 

n         작성 요령

가능하면 1:1로 작성 이름을 통일

 

n         인터페이스 작성 예

@interface ClassName : ItsSuperClass

{

instance variables declaration..

}

method declarations

@end

 

n         메소드 선언시 옵션

-

Instance method

+

Class method

              메소드 선언시 인스턴스와 클래스메소드 같은 이름으로 생성 가능

              메소드 이름과 인스턴스 변수도 같은 이름으로 생성 가능

 

n         메소드 선언 예

-선언

- (void) setWidth: (float) width height: (float) height;

-사용

id *myRect = [[Rectangle alloc] init];

[myRect setWidth:12.2 height:18.0];

-가변적 변수수를 가진 메소드 선언

- makeGroup:group, …;

 

n         interface import

interface import C #include와 동일하나, import가 똑 같은 것을 한번만 가져오는 것만 inclue와 다름.

 

n         implementation 작성예

@implementation ClassName : ItsSuperclass -> superclass 생략 가능

{

    instance variable declarations -> 생략 가능

}

method definitions

@end

              간단히 쓰면,

#import "ClassName.h"

 @implementation ClassName

method definitions

@end

 

n         다른 클래스 참조

인터페이스에 선언되지 않은 클래스를 사용할 때

상호참조의 문제를 해결하기 위해 @class 지시자를 사용.

@class Rectangle, Circle;

이것은 단지 컴파일러에 이것이 클래스 이름이라는 것만 알려주는 역할

 

n         인터페이스 특징

인터페이스파일은 클래스의 참조현황을 파악하기 쉽게함

인스턴스 개체를 따로 관리함으로서 보다 직관적인 OOP를 가능하게 함

 

n         instance변수들의 사용범위를 설명한 지시자

@private

instance변수의 범위를 그것이 선언된 class 한정한다.(상속불가)

@protected

instance변수의 범위를 선언되고, 상속된 class 한정한다. (상속가능)

@public

instance변수의 범위에 대한 제한을 없앤다. (상속가능)

 

n         instance변수 범위 지정의 이유

슈퍼클래스 변수와의 독립성을 유지함으로서 보다 완벽한 오브젝트화 가능

 

n         다른 객체에 속한 인스턴스 변수사용 예

선언구현부

@interface Sibling : NSObject

{

Sibling *twin;

int gender;

struct features *appearance;

}

참조구현부

- makeIdentification

{

if( !twin)

{

twin = [[Sibling alloc] init];

twin->gender = gender;

twin->appearance = appearance;

}

return twin;

}

 

 

영문 레퍼런스트를 정리하다가 갑자기 생겨난 쓸데없는 오기..ㅡ.ㅡ
도움 되려나~ 


Posted by 김반장78
,

요즘 이거 읽느라 프로젝트가 전혀 진행이 안된다..ㅡ.ㅡ
문서원본은 애플꺼고 번역자 정보도 안에 들어있으니 저작권은 문제없지 싶다.
프로그램용어에 울렁증 있어서 한글인데도 읽다보면 정신이 혼미해진다..
Posted by 김반장78
,