Object lifecycle, Autorelease
Object lifecycle
- Creating Object
- Memory Management (Retain Count)
- 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
Objective-C and Foundation Framework
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