보관물

Archive for the ‘Objective-C’ Category

Object lifecycle, Autorelease

2월 20, 2011 댓글 남기기

Object lifecycle

  1. Creating Object
  2. Memory Management (Retain Count)
  3. Destroying Object

Creating Object

  • +alloc
    object를 저장하기 위한 memory 할당
  • -init
    object 초기화

필요에 따라 -init에 해당하는 method를 구현할 수 있다.

-(id) initWithName:(NSString *)m_name {

if ( self = [super init]) {

name = m_name;

}

return self;

}

Memory Management

retain count는 Objective-C에서 memory를 관리하기위해 사용되는 값이며
최초 생성시 retain count는 1이 되고 더이상 object가 필요없을 때 retain count를 0으로 만들면 object는 해제된다.

  • +alloc, new
    object가 생성되면서 retain count가 1이 됨.
  • -copy
    object가 복사(value copy)되면서 retain count가 1이 됨.
  • retain
    retain count 1만큼 증가
  • release
    retain count 1만큼 감소

Destroying Object

retain count가 0이 되면 – dealloc이 자동으로 호출된다.
[super dealloc];을 호출하는걸 제외하고 dealloc을 직접적으로 호출하는 경우는 없다.

-(void) dealloc {

//ivar release
[name release];

//calls dealloc of superclass
[super dealloc];

}

Autorelease

alloc, new, copy로 생성되지 않은 object들 (예를 들면 NSString의 stringWithFormat:)은 autorelease형태로 create된다.

Autorelease로 지정된 object는 autorelease pool에서 알아서 release를 해주기 때문에 ownership을 갖게되도라도 이를 관리할 필요가 없다.
단 autorelease로 지정된 object를 retain, copy 하는 경우에는 release에 대한 책임을 져야한다.

Autorelease가 유용하게 쓰일때는 method 내에서 생성한 object를 return하는 경우이다.
자신이 생성한 object는 자신이 release하는게 기본이지만 method내에서 생성한 object를 return하는 경우에는 ownership이 외부로 넘어가게 되므로
더이상 release에 대한 책임을 질 수가 없게 된다.
이런경우 autorelease 지정을 하게되면 추후 사용하게 되지 않을 때(pool이 release될때) 자동으로 release가 되니 편리하다.

-(NSString *) makeName {

NSString *name = [[NSString alloc] initWithString:@”Andy”];

[name autorelease];

return name;

}

참고자료

iPhone Application Development (CS193P) – Winter 2010 : iTunes U
3. Custom Classes, Object lifecycle, Autorelease, Objective-C Properties

 

Custom classes, Properties

2월 20, 2011 댓글 남기기

Object Classes

Public Header (.h)

#import <Foundation/Foundation.h>

@interface Animal : NSObject
{

//instance variables
NSString *name;

}
//method declarations
-(NSString *)name;
-(void)setName:(NSString *)m_name;
@end

Private Implementation (.m)

#import “Animal.h”

@implementation Animal
-(NSString *)name {

return name;

}
-(void)setName:(NSString *)m_name {

name = m_name;

}
@end

Class내에서 선언된 method를 사용하고자 하는 경우 다음과 같은 형태로 사용한다.

[self setName:@”Andy”];

if ([self isDog]) {
//…
}

Properties

위의 sample code는 NSString 형태의 name이라는 변수에 대해서 getter/setter를 구현하였음.
이를 Properties와 Synthesize를 써서 같은 기능을 하도록 변경을 하면 다음과 같다.

Public Header (.h)

#import <Foundation/Foundation.h>

@interface Animal : NSObject
{

//instance variables
NSString *name;

}

@property (copy) NSString *name;

@end

Private Implementation (.m)

#import “Animal.h”

@implementation Animal

@synthesize name;

@end

ivars에서 정의한 이름과 property로 사용할 이름을 다르게 정의할 수도 있다.
아래의 sample code는 ivar는 _name으로 정의하였지만
property를 다음과 같이 정의함으로써 name으로 사용할 수있다.

Public Header (.h)

#import <Foundation/Foundation.h>

@interface Animal : NSObject
{

//instance variables
NSString *_name;

}

@property (copy) NSString *name;

@end

Private Implementation (.m)

#import “Animal.h”

@implementation Animal

@synthesize name = _name;

@end

property로 선언한 것을 self와 dot syntax를 활용할 수도 있다.

//self와 dot syntax를 사용한 경우
self.name = @”Lucy”;

//self와 dot syntax를 사용한 경우와 동일한 내용
[self setName:@”Lucy”];

//ivar에 직접 접근하는 경우 (accessor method를 사용안함)
name = @”Lucy”;

그러므로 self와 dot syntax를사용하고 setter를 별도로 구현하는 경우 다음의 경우를 주의해야한다.

-(void) setName:(NSString *)m_name {

//self.name은 [self setName:…]을 호출하므로 재귀적으로 무한루프에 빠지게됨
self.name = m_name;

}

참고자료

iPhone Application Development (CS193P) – Winter 2010 : iTunes U
3. Custom Classes, Object lifecycle, Autorelease, Objective-C Properties


 

Objective-C and Foundation Framework

2월 18, 2011 댓글 남기기

Objective-C

  • C의 superset
  • 단일 상속
    class는 단 하나의 superclass를 가짐
  • Protocol
  • Dynamic runtime
    Message dispatch
  • id
    정해지지 않은 object type으로 runtime시 형이 확정

Class는 instance를 생성하기 위한 blueprint

Message syntax

  • [receiver method];
  • [receiver method:argument];
  • [receiver method:arg1 andArg:arg2];

Dot syntax

Objective-C 2.0에서 소개되었으며 accessor methods를 편리하게 사용하는 방법

//message syntax
[anyObject height];
//Dot syntax
anyObject.height;

BOOL typedef

YES, NO의 값을 가짐

//아래 3가지 표현식은 모두 동일
if (flag == YES) {
}

if (flag) {
}

if (flag == 1) {
}

Selector

  • SEL
    Selector의 object type
  • C에서의 function pointer와 개념이 유사함

id anyObject;
//start라는 이름의 method를 selector로 지정
SEL sel = @selector(start:);

//anyObject가 sel에 해당하는 method에 응답할 수 있는지 확인
if ([anyObject respondeToSelector:sel]) {
//anyObject에서 sel에 해당하는 method를 실행
[anyObject performSelector:sel withObject:self];
}

Class introspection

  • isKindOfClass
    Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.
  • isMemberOfClass
    Returns a Boolean value that indicates whether the receiver is an instance of a given class.

Object 비교

  • Identity

if (obj1 == obj2) {
NSLog(@”Same exact object instance”);
}

  • Equality

if ([obj1 isEqual:obj2]) {
NSLog(@”Logically equivalent, but may be different object instances”);
}

Description

NSObject에서 -(NSString*) description; 형태로 구현되어 있음
Java의 toString과 유사

//Format string으로 사용시
[NSString stringWithFormat: @”Object is %@”, anyObject];

//log사용시
NSLog([anyObject description]);

Foundation framework

  • Values and Collection classes
  • User defaults
  • Archiving
  • Notifications
  • Undo manager ( > iPhone OS 3.0)
  • Tasks, timers, threads
  • File system, pipes, I/O, bundles

NSObject

Root class

String class

Unicode String지원

  • NSString
    Immutable class
  • NSMutableString
    NSString의 subclass

Format string을 사용하는 경우 %@와 같은 형태로 사용

NSLog(@”I am a %@, I have %d items”, [array className], [array count]);
//result : I am a NSArray, I have 5 items

Collections

  • Enumeration mechanism사용

for (Person *person in array) {
NSLog([person description]);
}

  • NSString과 유사하게 Immutable/Mutable 구분
    Mutable object는 과도하게 사용시 성능저하를 일으킬 수 있음
  • Array
    순서가 있는 object의 모음
  • Dictionary
    key-value 쌍으로 이루어진 object의 모음
  • Set
    순서가 없는 unique한 object의 모음

NSNumber

  • 일반적으로 Objective-C에서 사용하는 숫자형
  • NSValue의 subclass
  • Immutable

참고자료

Introduction to The Objective-C Programming Language
Object-Oriented Programming with Objective-C

원본자료

iPhone Application Development (CS193P) – Winter 2010 : iTunes U
2. Objective-C and Foundation Framework

Getting Started with Graphics and Animation

2월 18, 2011 댓글 남기기

iOS는 graphics와 animation을 실행하기위해 3가지  framework를 지원한다.

  • UIKit
    Objective-C class library.
    UI 제어, Animate, 2D drawing
  • Core Graphics
    C-Based API.
    Vector graphics, Bitmap images, PDF content
    (Quartz 2D는 2D drawing engine으로 사용되며 종종 Core Graphics와 동의어로 사용됨)
  • OpenGL ES
    Objective-C based API로 구현한 EAGL을 사용
    2D/3D drawing

The Basics

View Programming Guide for iOS
Drawing and Printing Guide for iOS

Deciding Which Frameworks to Use

Drawing Layered Content

Metronome 예제 참조
UIView Class Reference

Animating

MoveMe 예제 참조
Animations
Core Animation Programming Guide

Working With Images

UIImageView Class Reference
UIImage Class Reference
UIScrollView Class Reference
UIScrollViewDelegate Protocol Reference

Drawing Custom Content using Quartz 2D

Drawing and Printing Guide for iOS
CGContext Reference
Overview of Quartz 2D
Quartz 2D Programming Guide

Drawing With OpenGL ES

GLSprite 예제
OpenGL ES Overview
OpenGL ES Programming Guide for iOS

원본자료

Getting Started with Graphics and Animation