iOS - 3Sanghun Han
EZNIX 솔루션개발 연구원
Obj-C - Foundation Class iOS -TableView
Foundation Class
Type?• Array
• Data
• Dictionary
• Set
• String
• ..etc
불변, 가변
• 불변, 가변 객체 2종류를 지원
!
• immutable, mutable 객체로 구분
불변, 가변
• NSString
• 수정 불가
• NSMutableString
• 수정 가능
String
• Unicode
• unichar
String• initWithUTF8Strings:(const char *)bytes
• initWithCString:(const char *) encoding:(NSStringEncoding)
• initWithFormat:(NSString *)format, ...
!
• init->string, Convenience Constructor
String• Compare, caseInsensitiveCompare
• NSComparisonResult - String 비교
• NSOrderedAscending
• NSOrderedSame
• NSOrderedDescending
• (BOOL)isEqualToString:(NSString *)string
String• NSRange
• 검색, 치환 등에 사용되는 Structure
• location, length
• rangeOfString:(NSString *)string
• stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement
• stringByReplacingOccurrencesOfString(NSString *) target withString:(NSString *)replacement
String• intValue, integerValue, floatValue, boolValue
• 파일 경로 조작을 위한 메서드 제공
• lastPathComponent, pathExtension...etc.
• 파일 내용 스트링으로 바로 로드 가능
• initWithContentsOfFile: encoding: error
• writeToFile: atomically: encoding: error
Mutable String• NSString 의 조작 가능한 Ver
• initWithCapacity:(NSUInteger)capacity
• appendString:
• appendFormat: ...
• 대부분의 Mutable Class들은 이와 같은 조작법이 비슷하며, 더하고, 빼고, 치환하는 로직들을 지원한다.
NSData• Byte 배열 Wrapper
• initWithBytes:(const void *)bytes length:(NSUInteger)length
• initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)flag
• Void 배열을 복사하고 생성하는지 안하는지와, 배열의 해제 타임 ( free ) 을 NSData가 관리하는 지에 대한 결정을 할 수 있는 컨스트럭터들이다.
NSData• getBytes:(void *)buffer
• buffer에 Data를 '복사'
• (const void *)bytes
• Data 배열 리턴
• NSString과 마찬가지로 파일 입,출력이 가능함
• initWithContentsOfFile:(NSString *)path options:(NSUInteger)mask error(NSError **)errorPtr
• writeToFile:(NSString *)path atomically:(BOOL)flag
NSArray
• 배열 클래스, 오브젝트 나열로 생성 가능
• initWithObjects:(id)firstobj, ....
• initWithArray:(NSArray *)array
• Literal 추가
• @[Objects, ...]
NSArray• 배열 접근 메서드
• count
• lastObject
• objectAtIndex:(NSUInteger)index
• 비교
• isEqualToArray:(id)object
NSArray• 추가도 가능하지만, 되도록이면 MutableArray에서 addObject: 를 호출하는 것이 편하다.
!
• (NSArray *)arrayByAddingObject:(id)anObject;
• 대부분의 Immutable Class들도 이렇게 추가, 제거를 제공하지만 추가, 제거시마다 객체가 생성되고 소멸되는 사이클이 반복되기 때문에 사용성이 좋지 않다.
NSArray
• 배열의 정렬
• (NSArray *)sortedArrayUsingSelector:(SEL)comparator
• 정렬 메서드로, 정해진 comparator를 통해서 정렬된다. comparator는 요소 간 비교에 쓰이며, 결과로 NSComparisonResult를 리턴하는 메서드이다.
NSArray
• 파일 입출력은 plist 파일로 제공된다.
• Data와 동일하게 initWithContentsOfFile 사용
• 고속 열거 사용 가능
• for (id obj in group) do Something;
• group은 Array, Set, Dictionary 등등이 가능함
NSMutableArray
• initWithCapacity, array 메서드로 생성
• 사용량에 따라서 자동으로 더 늘어나므로, 초기 값에 연연할 필요는 없다.
NSMutableArray
• addObject:(id)obj
• removeLastObject
• replaceObjectsInRange
• 치환, 삭제, 삽입에 관련된 여러 메서드를 제공
NSMutableArray
• Reference Counting 방식에서는, addObject로 객체를 추가한 경우에 retain이 자동으로 호출되며 Array가 객체의 OwnerShip을 가진다.
!
• 집합 클래스인 NSSet은 NSArray와 행동 양식이 매우 유사함
NSDictionary• Key-Value로 이루어진 클래스
• Entry
!
• initWithObjects:(NSArray *)objects forKeys:(NSArray *) keys
• initWithObjectsAndKeys:(id)object, (id)key, ...
NSDictionary
• Literal 선언
• @{Key : Obj, …}
NSDictionary
• 접근 메서드
• (id) objectForKey: (id) key
• (NSArray *) allKeys
• (NSArray *) allKeysForObject
NSDictionary
• 파일 입, 출력은 plist로 이루어짐
• Data와 동일하게 initWithContentsOfFile 사용
• writeToFile 또한 동일하게 사용
NSMutableDictionary
• 초기화
• initWithCapacity - 자동으로 늘어남
• 조작
• (void)setObject: (id)object forKey:(id)key
• (void)removeObjectForkey:(id)key
NSNumber
• 숫자 관련 Wrapper Class
• 기본 형을 객체로 취급할 때 꼭! 필요한 클래스
NSNumber
• initWith자료형:(자료형)value
• BOOL, char, double, float, int, NSInteger, long, long long, short, unsigned char, unsigned int, NSUInteger, unsigned long, unsigned long long, unsigned short 를 지원한다. ( 다함 )
NSNumber
• 접근할 때는 간단하게
• 자료형Value 메시지를 보내면 된다.
NSNumber
• Literal을 제공함
• NSNumber *n = @2;
• NSNumber *n = @2.5;
NSValue, NSNull
• NSValue는 Primitive Type이 아닌 포인터, 사이즈, Range등을 랩핑할 때 사용
• NSNull은 빈 객체를 활용할 때 사용
UITableView
UITableView
• 가장 많이 쓰이는 View중 하나
!
• 안드로이드의 ListView의 역할
!
• 개개의 Cell로 이루어짐
UITableView• Delegate
• 선택, 입력 처리 등을 처리
• 데이터를 직접 처리한다기보다는 User Interaction에 촛점을 맞춘 메서드들이 주를 이룬다.
• Data Source
• 화면에 표시되는 데이터 및 View를 제공해주고, 데이터를 뷰에 맵핑하는 작업을 해주는 메서드들이 주를 이룬다
UITableView• UITableViewDataSource - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath Table View의 Cell 들을 생성해주는 함수 Table View Cell을 생성하는 방법은 Story Board 를 사용하는 경우는 다음처럼 identifier로 지정된 Cell을 가져오면 nil이 넘어오는 경우 없이 무조건 잘 넘어오게 된다. 다만, Story Board를 사용하지 않는 경우는 아래처럼 nil인지를 한 번 체크하고, xib에서 로드하는 방식을 사용하여야 한다. !!!!!!!!!!!!* dequeueReusableCellWithIdentifier 메서드는 셀을 재사용하기 위한 메서드로서, 지정된 identifier로 큐잉된 셀을 가져온다. !- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 테이블 뷰의 Section 갯수를 알려주는 메서드 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 테이블 뷰의 각 Section의 Row갯수를 알려주는 메서드 !- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 테이블 뷰의 Section Header에 들어갈 Title 제목을 알려주는 메서드 - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section 테이블 뷰의 Section Footer에 들어갈 Title 제목을 알려주는 메서드 !- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView 테이블 뷰의 Section들을 우측에 리스트로 띄워서 빠른 접근을 가능하게 해주는 텍스트를 제공하는 메서드이다.
UITableView• UITableViewDataSource - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath ! Cell이 EditMode가 되었을 때, Delete Btn이나 insertion 버튼을 누를 경우에 호출되는 메서드로, 알맞은 작업을 처리하도록 작성해야하는 메서드이다. !- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath ! Cell이 EditMode에서 위치가 이동되었을 때 호출되는 메서드로, 여기서도 알맞은 작업을 처리해주면 된다. Edit Mode에서 위 함수가 오버라이드 되어 있지 않다면 우측에 이동 가능 표시는 나타나지 않는다.
UITableView• UITableViewDelegate -(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath Cell을 선택할 때 불려지는 메서드로, 몇 번째 셀이 불렸는지 index Path의 Section과 Row를 참조해서 판단하고 작업하면 된다. 가장 많이 사용되는 메서드이며, 셀의 입력을 받는 부분이기 때문에 중요한 메서드이다. !- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section 이 3가지 메서드는 UITableViewCell의 Row Height, Section의 Height, Footer의 Height를 동적으로 정해주는 메서드이다. indexPath와 매칭되는 데이터를 찾고, 데이터에 맞춰서 셀을 늘려주는 방법으로 사용하며 매우 유용하다. !- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section 오른쪽 화면처럼 Footer나 Header를 Custom한 View로 구성하고 싶을 때 사용하는 메서드이다. UITableViewDataSource의 titleForHeaderInSection, titleForFooterInSection 메서드로 입력할 데이터를 가져오고, 알맞게 View를 생성하고 뿌려서 사용하는 방법으로 많이 사용된다. !- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath UITableViewCellEditingStyle을 구분하는 메서드로 다음 3개의 값이 있고, 결정된 값에 따라 Edit Mode로 진입 시에 View의 Output이 결정된다. ! UITableViewCellEditingStyleNone - 변화 없음 UITableViewCellEditingStyleDelete - Delete 모드 UITableViewCellEditingStyleInsert - Insert 모드 !!!
UITableView• UITableViewDelegate !- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath: (NSIndexPath *)indexPath Edit Mode로 진입 시에 UITableViewCellEditingStyleNone으로 지정된 Cell들에 대해서 indentation이 이루어질 것인가, 아닌가에 대해서 결정하게 되는 펑션이다. return NO로 설정되었다면, 다음과 같이 Edit Mode에서 indentation이 되지 않는다. !- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath EditMode에서 Delete 버튼의 타이틀을 지정하는 메서드이다. 지정해주면 다음처럼 지정한 값으로 변경된다. !!!!!!!!!!!!!!!- (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath - (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath Swipe-Action 으로 들어오는 ( 셀을 오른쪽이나 왼쪽으로 밀면 ) edit mode시 불리는 메서드로, 한 셀에 관해서만 edit Mode로 진입될 때 작동하는 함수이다. 참고로, 여기서 Delete를 누르면 마찬가지로 Data Source의 commitEditingStyle 메서드가 호출된다.
UITableView• UITableViewDelegate !!!!!!!!!!!!- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath Cell Long-click시에 위와 같은 메뉴를 띄울 지 안 띄울지 결정하는 메서드 !- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender action 중 어떤 것을 지원 할 지 결정하는 메서드로, copy와 paste를 지원하려면 다음처럼 작성하면 된다. ! return action == @selector(copy:) || action == @selector(paste:); ! 참고로, copy, paste, cut 3가지를 메뉴에서 지원한다. !!- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender 실제로 메뉴의 버튼을 눌렀을 때 호출되는 메서드로, 여기서 적절한 처리를 해주면 된다. !
Top Related