It’s me. Right.
Hello.ENTP.World
It’s me. Right.
전체 방문자
오늘
어제
  • 분류 전체보기 (45)
    • 멋쟁이사자처럼 앱스쿨 1기 (18)
    • 2024 Apple Developer Academ.. (10)
    • 개발 with Apple (8)
    • Flutter (1)
    • 알고리즘 (4)
    • 디자인 (0)
    • 앱스토어 출시 (1)
    • 영어공부 (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Apple Developer Academy
  • 협업
  • swift cicd
  • git xcodecloud
  • git xcode cloud
  • 아키텍처
  • 애플아카데미
  • 애플디벨로퍼아카데미
  • 코딩테스트
  • 동기
  • git cicd
  • 알고리즘
  • 코테
  • xcode cloud workflow
  • ios
  • xcode 팀 계정
  • 백준
  • xcode 배포 자동화
  • 개발
  • xcode cicd
  • 개발자
  • 좋은 회고
  • 회고
  • swiftUI
  • xcode cloud appstoreconnect
  • xcode cloud 계정 권한
  • Xcode cloud
  • Xcode
  • xcoud cloud cicd
  • xcodcloud

최근 댓글

최근 글

티스토리

반응형
hELLO · Designed By 정상우.
It’s me. Right.

Hello.ENTP.World

[멋쟁이사자처럼] 앱스쿨 1기 - Objective-C (17일차 22.10.11)
멋쟁이사자처럼 앱스쿨 1기

[멋쟁이사자처럼] 앱스쿨 1기 - Objective-C (17일차 22.10.11)

2022. 10. 11. 17:55
반응형

드디어어어어~~~~ 내 블로그를 구글에서 인식을 해주기 시작했다ㅎㅎ 멋쟁이 사자처럼을 하고 약 1달이 지났으니 google search console에서 url 색인이 완료되는 것까지 한달이 걸렸다... 처음에 오류에 대해서 구글에 엄청 검색해 봤는데 한달정도 지나면 인식이 된다는 글을 본 적이 있었는데 진짜 https, 직접 url 요청 등 다 해봤는데 안되더니 정말 한달이 걸릴줄 몰랐다... 이제 구글에 블로그명이나 내가 쓴 내용을 검색 해보니 아주 잘 검색되어서 블로그 작성에 더 의지가 뿜뿜해지기 시작한다ㅎㅎ 오늘도 화이팅@.@


1. 오전일정 : Objective-C

구조체

  • Objective-C 배열을 사용하면 같은 종류의 여러 데이터 항목을 보유할 수 있는 변수 유형을 정의할 수 있지만 구조체는 다른 종류의 데이터 항목을 결합할 수 있는 Objective-C 프로그래밍에서 사용할 수 있는 또 다른 사용자 정의 데이터 유형

구조체 정의

  • 구조체 태그 는 선택 사항이며 각 멤버 정의는 int i와 같은 일반 변수 정의입니다(또는 float f; 또는 다른 유효한 변수 정의)
    -> 메소드, 초기화 등 기능 구현 불가능
  • 구조 정의 끝에서 마지막 세미콜론 앞에 하나 이상의 구조 변수를 지정할 수 있지 만 선택 사항

구조체 멤버 접근

  • 구조체 멤버에 엑세스 하기 위해서는 멤버 엑세스 연산자(.)을 사용
struct Books {                  //(Books)구조체 이름 != type 이름은 아님
 NSString *title;
 NSString *author;
 NSString *subject;
 int book_id;
} book;
#import <Foundation/Foundation.h>

struct Books {
    NSString *title;
    NSString *author;
    NSString *subject;
    int bookId;
};

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        struct Books book1;
        struct Books book2;
        
        book1.title = @"C언어 프로그래밍";
        book1.author = @"데니스 리치";
        book1.subject = @"C언어 학습 공식도서";
        book1.bookId = 1234567;
        
        NSLog(@"%@", book1.title);
        NSLog(@"%@", book1.author);
        NSLog(@"%@", book1.subject);
        NSLog(@"%d", book1.bookId);
    }
    return 0;
}

 

함수의 인수로서의 구조체

#import <Foundation/Foundation.h>

struct Books {
    NSString *title;
    NSString *author;
    NSString *subject;
    int bookId;
};

@interface SampleClass : NSObject               //클래스 선언
- (void)printBookInfo:(struct Books)book;
@end

@implementation SampleClass                     //클래스 구현

- (void)printBookInfo:(struct Books)book {
    NSLog(@"%@", book.title);
    NSLog(@"%@", book.author);
    NSLog(@"%@", book.subject);
    NSLog(@"%d", book.bookId);
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        struct Books book1;
        
        book1.title = @"C언어 프로그래밍";
        book1.author = @"데니스 리치";
        book1.subject = @"C언어 학습 공식도서";
        book1.bookId = 1234567;
        
        SampleClass *sampleClass = [[SampleClass alloc] init];      //메모리에 클래스 생성 및 초기화
        [sampleClass printBookInfo:book1];                          //클래스에 book1 넣어줌
        
    }
    return 0;
}

 

구조체에 대한 포인터

  • 위 class로 만든 구조체를 *포인터를 사용해서 재구성해봄
  • C언어에서 call by reference를 위해서는 *를 끼고 사용함
#import <Foundation/Foundation.h>

struct Books {
    NSString *title;
    NSString *author;
    NSString *subject;
    int bookId;
};

@interface SampleClass : NSObject
- (void)updateBookInfoTitle:(struct Books)books;
- (void)printBookInfo:(struct Books)books;

- (void)updateBookTitle:(struct Books *)book;
- (void)descriptionBookInfo:(struct Books *)book;
@end

@implementation SampleClass

- (void)updateBookInfoTitle:(struct Books)books {
    books.title = @"Hello World";
}

- (void)printBookInfo:(struct Books)books {
    NSLog(@"%@", books.title);
    NSLog(@"%@", books.author);
    NSLog(@"%@", books.subject);
    NSLog(@"%d", books.bookId);
}

- (void)updateBookTitle:(struct Books *)books {
    books->title = @"Hello Objective-C";
}

- (void)descriptionBookInfo:(struct Books *)books {
    NSLog(@"%@", books->title);
    NSLog(@"%@", books->author);
    NSLog(@"%@", books->subject);
    NSLog(@"%d", books->bookId);
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        struct Books book1;
        
        book1.title = @"C언어 프로그래밍";
        book1.author = @"데니스 리치";
        book1.subject = @"C언어 학습 공식도서";
        book1.bookId = 1234567;
        
        SampleClass *sampleClass = [[SampleClass alloc] init];
        
        // 값으로 복제시킬 매개변수 - call by value
        [sampleClass updateBookInfoTitle:book1];
        [sampleClass printBookInfo:book1];
        
        // 포인터 참조값으로 알려주고 직접 건드리게 할 매개변수 - call by reference
        [sampleClass updateBookTitle:&book1];
        [sampleClass descriptionBookInfo:&book1];
    }
    return 0;
}

 

비트 필드

  • 통신 프로그램, 압축 프로그램 등 low 영역을 다루는 경우에 사용하고, 잘 사용하지는 않는다.

 

전처리기

  • #define -> 모든 전처리기 명령은 파운드 기호(#)로 시작함
  • Objective-C 전처리기는 컴파일러의 일부가 아니지만 컴파일 프로세스의 별도 단계
    -> Objective-C 전처리기는 텍스트 대체 도구이며 실제 컴파일 전에 필요한 전처리를 수행하도록 컴파일러에 지시
  • Objective-C 전처리기를 OCPP(Objective-C PreProcessors)라고 부른다.
  • 공백이 아닌 첫 번째 문자여야 하며 가독성을 위해 전처리기 지시문은 첫 번째 열에서 시작해야 한다.

멋쟁이 사자처럼 앱스쿨 1기, 강사님 강의자료

 

typedef

  • Objective-C 프로그래밍 언어는 typedef 라는 키워드 를 제공하여 유형에 새 이름을 지정하는 데 사용
typedef struct Books BOOK;        //Books로 정의된 구조체를 BOOK로 부를 것이다

struct Books {
    NSString *title;
    NSString *author;
    NSString *subject;
    int bookId;
} BOOK;                           //이렇게 축약형으로 선언할 수도 있다

 

typedef와 #define 비교

  • typedef는 컴파일러, #define은 전처리기(에 의해 처리되는 컴파일러)로 수행된다.
  • 컴파일러를 통한 직접 수행이 더 정확한 처리가 가능하기 때문에 typedef를 사용 권장
//define 코드

#import <Foundation/Foundation.h>

#define TURE 1
#define FALSE 0

int main() {
     NSLog( @“Value of TURE : %d\n", TRUE);               //컴파일 전에 전처리기에 의해서 TRUE = 0로 처리됨
     NSLog( @“Value of FALSE : %d\n", FALSE);             //컴파일 전에 전처리기에 의해서 FALSE = 1로 처리됨
     return 0;
}

 

오류처리

  • Objective-C 프로그래밍에서 오류처리 Foundation 프레임워크에서 사용할 수 있는 NSError 클래스와 함께 제공
  • NSError 개체는 오류 코드 또는 오류 문자열만 사용하여 가능한 것보다 더 풍부하고 확장 가능한 오류 정보를 캡슐화한다.
  • NSError 객체의 핵심 속성은 오류 도메인(문자열로 표시), 도메인 특정 오류 코드 및 응용 프로그램 특정 정보를 포함한다.

2. 오후일정 : Objective-C

클래스

#import <Foundation/Foundation.h>

// Person 클래스 정의
@interface Person : NSObject {
    NSString *personName;
    NSInteger personAge;
}

- (id)initWithName:(NSString *)name andAge:(NSInteger)age;
- (void)print;
@end

@implementation Person

- (id)initWithName:(NSString *)name andAge:(NSInteger)age {
    self = [super init];
    
    personName = name;
    personAge = age;
    
    return self;
}

- (void)print {
    NSLog(@"Name: %@", personName);
    NSLog(@"Age: %ld", personAge);
}

@end

// Person을 상속받은 Employee 클래스 정의
@interface Employee : Person {
    NSString *employeeEducation;
}

- (id)initWithName:(NSString *)name andAge:(NSInteger)age andEducation:(NSString *)education;
- (void)print;

@end

@implementation Employee

- (id)initWithName:(NSString *)name andAge:(NSInteger)age andEducation:(NSString *)education {
    self = [super initWithName:name andAge:age];
    employeeEducation = education;
    return self;
}

- (void)print {
    [super print];
    NSLog(@"Educaiton: %@", employeeEducation);
}

@end


int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Person *person = [[Person alloc] initWithName:@"Ned" andAge:13];
        [person print];
        
        Employee *employee = [[Employee alloc] initWithName:@"홍길동" andAge:15 andEducation:@"서당"];
        [employee print];
    }
    return 0;
}

 

클래스(Swift)

import Foundation

//person 클래스 정의
class Person {
    //1.이름
    var name : String = ""
    var age : Int = 0
    
    //초기화
    init(name: String, age: Int){           //초기화 작업
        self.name = name
        self.age = age
    }
    
    func printValue() {
        print(name)
        print(age)
    }
    
}

//person 클래스를 상속받은 employee 클래스 정의
class Employee : Person {
    
    var education : String = ""
    
    init(education : String, name: String, age: Int) {
        self.education = education
        
        super.init(name: name, age: age)
    }
    
    override func printValue() {
        super.printValue()
        print(education)
    }
    
}

//Employee(education: "school", name: "jina", age: 25)

var person = Person(name: "jina", age: 23)
person.printValue()

var employee = Employee(education: "school", name: "jina", age: 25)
employee.printValue()

 

다형성

  • 일반적으로 클래스의 계층 구조가 있고 상속으로 관련되 어 있을 때 발생합니다.
  • Objective-C 다형성은 멤버 함수에 대한 호출이 함수를 호출하는 객체의 유형에 따라 다른 함수 실행을 의미함
#import <Foundation/Foundation.h>

// 윤곽 클래스 정의
@interface Shape : NSObject {
    CGFloat area;   // 넓이
}

- (void)printArea;
- (void)calculateArea;
@end

@implementation Shape
- (void)printArea {
    NSLog(@"The area is %f", area);
}

- (void)calculateArea {
    // 아직 모르겠음
}
@end


// 윤곽을 상속받은 정사각형 클래스 정의
@interface Square : Shape {
    CGFloat length; // 정사각형 변의 길이
}

- (id)initWithSide:(CGFloat)side;
- (void)calculateArea;
@end

@implementation Square
- (id)initWithSide:(CGFloat)side {
    self = [super init];
    length = side;
    return self;
}

- (void)calculateArea {
    area = length * length;
}
@end

// 윤곽을 상속받은 직사각형 클래스 정의
@interface Rectangle : Shape {
    CGFloat length;
    CGFloat breadth;
}

- (id)initWithLength:(CGFloat)length andBreadth:(CGFloat)breadth;
@end

@implementation Rectangle
- (id)initWithLength:(CGFloat)length andBreadth:(CGFloat)breadth {
    self = [super init];
    self->length = length;
    self->breadth = breadth;
    return self;
}

- (void)calculateArea {
    area = length * breadth;
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Shape *shape = [[Shape alloc] init];
        [shape printArea];
        
        Square *square = [[Square alloc] initWithSide:10.0];
        [square calculateArea];
        [square printArea];
        
        Rectangle *rectangle = [[Rectangle alloc] initWithLength:10.0 andBreadth:5.0];
        [rectangle calculateArea];
        [rectangle printArea];
    }
    return 0;
}

 

다형성(Swift)

class Shape {
    var area : Float = 0.0
    
    init(area: Float = 0.0) {           //상속받는 Class에서 area를 받아오지 않도록 구현하기 위해서, 기본값까지 정의해줌
        self.area = area
    }
    
    func printArea() {
        print(area)
    }
    
    func calculateArea() {
        
    }
}

class Square : Shape {
    var length : Float = 0.0
    
    init(length : Float) {
        self.length = length
    }
    
    override func printArea() {
        super.printArea()
        print(length)
    }
    
    override func calculateArea() {
        area = length * length;
        print("area = \(area)")
    }
}

class Rectangle : Shape {
    var length : Float = 0.0
    var breadth : Float = 0.0
    
    init(length : Float, breadth : Float) {
        self.length = length
        self.breadth = breadth
    }
    
    override func printArea() {
        super.printArea()
        print(length)
        print(breadth)
        
    }
    
    override func calculateArea() {
        area = length * breadth;
        print("area = \(area)")
    }
}

var square = Square(length : 5.0)
square.calculateArea()

var rectangle = Rectangle(length : 10.0, breadth: 6.0)
rectangle.calculateArea()

 

수업에서 요구하는 내용과는 다른 방향이지만.... 과정 및 결과값만 봤을 때 위에서 불필요한 코드들을 필요한 부분만 정리해 보았다...

getter & protocol

protocol Shape {
    var area : Float{ get }
    func printArea()
}

class Square : Shape {
    var length : Float = 0.0
    var area : Float{
        get {
            return length * length
        }
    }
    init(length : Float) {
        self.length = length
    }
    
    func printArea() {
        print("area(length(\(length) ^ 2) = \(area)")
    }
    
}

class Rectangle : Shape {
    var length : Float = 0.0
    var breadth : Float = 0.0
    
    var area : Float{
        get {
            return length * breadth
        }
    }
    
    init(length : Float, breadth : Float) {
        self.length = length
        self.breadth = breadth
    }
    
   func printArea() {
        print("area(length(\(length)) * breadth(\(breadth)) = \(area)")
    }
    

}

var square = Square(length : 5.0)
square.printArea()

var rectangle = Rectangle(length : 10.0, breadth: 6.0)
rectangle.printArea()

3. 오늘의 리뷰

혼자 끄적끄적 코드를 이렇게 바꿔보고 저렇게 바꿔보고 했는데 뭔가 깔끔하게 결과가 나온 것 같아서 뿌듯하다!
프로그래머스도 String... 대체 swift String은 평범하게(내가 생각하는 평범 = Python) 사용할 수 없을까.......

수업 끝나고 오늘도 String 문법을 공부하기 위해서 열심히 달려봐야지~~ 그럼 오늘도 모두 고생 많았습니다!!!

 

반응형

'멋쟁이사자처럼 앱스쿨 1기' 카테고리의 다른 글

[멋쟁이사자처럼] 앱스쿨 1기 - Json parsing & Async & Await (22.11.22)  (2) 2022.11.22
[멋쟁이사자처럼] 앱스쿨 1기 - SwiftUI (22일차 22.10.18)  (2) 2022.10.18
[멋쟁이사자처럼] 앱스쿨 1기 - Objective-C (16일차 22.10.07)  (2) 2022.10.07
[멋쟁이사자처럼] 앱스쿨 1기 - Objective-C (15일차 22.10.06)  (2) 2022.10.06
[멋쟁이사자처럼] 앱스쿨 1기 - 클로저&이스케이프 클로저 (14일차 22.10.05)  (4) 2022.10.06
    '멋쟁이사자처럼 앱스쿨 1기' 카테고리의 다른 글
    • [멋쟁이사자처럼] 앱스쿨 1기 - Json parsing & Async & Await (22.11.22)
    • [멋쟁이사자처럼] 앱스쿨 1기 - SwiftUI (22일차 22.10.18)
    • [멋쟁이사자처럼] 앱스쿨 1기 - Objective-C (16일차 22.10.07)
    • [멋쟁이사자처럼] 앱스쿨 1기 - Objective-C (15일차 22.10.06)
    It’s me. Right.
    It’s me. Right.
    개발자가 되고싶은 코린이의 천방지축 얼렁뚱땅 개발일기

    티스토리툴바