안녕하세요 진코드93입니다~!
이날도 Object-C 예제코드로 학습을 진행했는데요 역시... 배울수록 느끼는거지만 Swift가 짱입니다...ㅎ
그럼 바로 시작하도록 할께요~!!
오늘도 역시나 C#으로 적혀있지만 Objective-C 코드입니다 참고해주세요 ㅎㅎ
구조체 예제
#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;
}
typedef 예제
#import <Foundation/Foundation.h>
// Person 구조체를 정의해서 타입이름으로 쓰고 싶다면
typedef struct _Person {
float height;
int weight;
} Person;
// BMI 계산 함수
float calcBMI(Person person) {
// NSLog(@"height: %f", person.height);
// NSLog(@"weight: %d", person.weight);
return person.weight / (person.height * person.height);
};
int main(int argc, const char * argv[]) {
@autoreleasepool {
// struct Person person;
Person person;
person.height = 1.65;
person.weight = 55;
NSLog(@"height: %f", person.height);
NSLog(@"weight: %d", person.weight);
NSLog(@"BMI : %f", calcBMI(person));
}
return 0;
}
타입캐스팅 예제
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
int sum = 17;
int count = 5;
// int와 int의 나눗셈이라 int라고 결과를 생각할 수 있음
NSLog(@"Value of mean : %d", (sum / count));
// 강제로 위 계산 결과를 float값으로 각각 타입캐스팅 변환처리해준다면? 결과는 float 타입이 된다.
NSLog(@"Value of mean : %f", ((float)sum / (float)count));
}
return 0;
}
객체와 클래스 예제
#import <Foundation/Foundation.h>
@interface Box : NSObject {
double length; // 길이
double breadth; // 폭
double height; // 높이
}
//@property(nonatomic, readwrite) double length;
//@property(nonatomic, readwrite) double breadth;
@property(nonatomic, readwrite) double height;
- (double)volume;
@end
@implementation Box
// 선언된 프로퍼티를 가장 쉽게 구현부에서 만들어주는 방법
//@synthesize length;
//@synthesize breadth;
@synthesize height;
// 초기화 처리후 반환될 인스턴스는 id라고 통칭된다.
- (id)init {
self = [super init];
self->length = 1.0;
self->breadth = 1.0;
return self;
}
- (double)volume {
return length * breadth * height;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Box *box1 = [[Box alloc] init];
Box *box2 = [[Box alloc] init];
box1.height = 5.0;
box2.height = 10.0;
NSLog(@"Volume of Box1 : %f", [box1 volume]);
NSLog(@"Volume of Box2 : %f", [box2 volume]);
}
return 0;
}
상속 예제
#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로 구현해보기)
// 해당 코드는 Swift로 작성되었습니다.
// 코드블럭이 하나의 글 당 하나의 언어만 적용이 되네요 ㅠㅠ
// super class Person 정의
class Person {
var personName: String = ""
var personAge: Int = 0
// 초기화
init(name: String, age: Int) {
self.personName = name
self.personAge = age
}
// print
func displayPerson() {
print("Name: \(personName)")
print("Age: \(personAge)")
}
}
// Person 상속 받은 Employee class
class Employee: Person {
var employeeEducation: String = ""
// 초기화
init(name: String, age: Int, education: String) {
self.employeeEducation = education
super.init(name: name, age: age)
}
// print
override func displayPerson() {
super.displayPerson()
print("Education: \(employeeEducation)")
}
}
var person = Person(name: "Ned", age: 13)
person.displayPerson()
var employee = Employee(name: "홍길동", age: 15, education: "서당")
employee.displayPerson()
// => 역시... Swift가 훨씬 편하다...ㅎ
다형성 예제
#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로 구현해보기)
// 해당 코드는 Swift로 작성되었습니다.
// 코드블럭이 하나의 글 당 하나의 언어만 적용이 되네요 ㅠㅠ
class Shape {
var area: CGFloat = 0.0
func printArea() {
print("The area is \(area)")
}
func calculateArea() {
// 아직 모르겠음
}
}
class Square: Shape {
var length: CGFloat = 0.0
init(side: CGFloat) {
super.init()
length = side
}
override func calculateArea() {
super.calculateArea()
area = length * length
}
}
class Rectangle: Shape {
var length: CGFloat = 0.0
var breadth: CGFloat = 0.0
init(length: CGFloat, breadth: CGFloat) {
super.init()
self.length = length
self.breadth = breadth
}
override func calculateArea() {
super.calculateArea()
area = length * breadth
}
}
let square: Square = Square(side: 10.0)
square.calculateArea()
square.printArea()
let rectangle: Rectangle = Rectangle(length: 10.0, breadth: 5.0)
rectangle.calculateArea()
rectangle.printArea()
모듈 예제
#import <Foundation/Foundation.h>
@interface Adder : NSObject
//@property(nonatomic, readonly) NSInteger total;
- (id)initWithInitialNumber:(NSInteger)initialNumber;
- (void)addNumber:(NSInteger)newNumber;
- (NSInteger)getTotal;
@end
@implementation Adder {
NSInteger total;
}
//@synthesize total;
- (id)initWithInitialNumber:(NSInteger)initialNumber {
self = [super init];
total = initialNumber;
return self;
}
- (void)addNumber:(NSInteger)newNumber {
total = total + newNumber;
}
- (NSInteger)getTotal {
return total;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Adder *adder = [[Adder alloc] initWithInitialNumber:10];
[adder addNumber:5];
[adder addNumber:4];
// NSLog(@"The total is %ld", adder.total);
NSLog(@"The total is %ld", [adder getTotal]);
}
return 0;
}
카테고리 예제
#import <Foundation/Foundation.h>
// 카테고리 만들기 예제
@interface NSString(MyAddtions)
+(NSString *)getCopyRightString; // 저작권자 이름 알려주는 클래스 메서드
-(NSString *)getName;
@end
@implementation NSString(MyAddtions)
+(NSString *)getCopyRightString {
return @"저작권자 멋쟁이사자처럼 2022";
}
-(NSString *)getName {
return @"ned";
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"%@", [NSString getCopyRightString]);
NSString *temp = [[NSString alloc] init];
NSLog(@"%@", [temp getName]);
}
return 0;
}
'멋쟁이 사자처럼 앱스쿨 1기 > 회고록' 카테고리의 다른 글
멋사 앱 스쿨 1기 17일차 회고록/TIL (22.10.07) - Objective-C (0) | 2022.10.17 |
---|---|
멋사 앱 스쿨 1기 16일차 회고록/TIL (22.10.06) - Objective-C (0) | 2022.10.17 |
멋사 앱 스쿨 1기 15일차 회고록/TIL (22.10.05) - 클로저, Objective-C 맛보기 (0) | 2022.10.14 |
멋사 앱 스쿨 1기 14일차 회고록/TIL (22.10.04) - 에러 핸들링, Swift 심화 (1) | 2022.10.13 |
멋사 앱 스쿨 1기 13일차 회고록/TIL (22.09.30) - DevOps, Git (0) | 2022.10.12 |