Objective-C 기본 문법 복습 - 1

준우·2024년 7월 24일

Objective-C 이야기

목록 보기
13/19
post-thumbnail

Basic Grammer

Log 출력

  • 단순 메시지 출력
NSLOG(@"Hello World!!");
  • 변수 출력
NSLOG(@"변수명(INT 타입)이 출력됩니다: %i", 변수명);
NSLOG(@"변수명(FLOAT 타입)이 출력됩니다: %f", 변수명);
  • 두 개의 변수 출력
NSLOG(@"변수명1: %i과 변수명2: %f가 출력됩니다.", 변수명1, 변수명2); 

주석 처리

// 한 줄 주석 처리

/* 
	여러 줄 주석 처리
*/

기본 변수

  • INT, FLOAT, CHAR, BOOL 변수들은 원시 변수라 부르며, 선언시 크기가 정해져 있어. * 을 안 붙여도 됨.

INT

int myInt = 3;

FLOAT

float myFloat = 3.3;

BOOL

BOOL myBool = true;

CHAR

char myChar = 'c';

String 변수

  • String 변수는 Int, float, bool, char 변수들과 다르게 크기가 정해져 있지 않음.
    그래서 변수명 앞에 * 을 붙여야 함.
  • String 변수 예제
NSString* myString = @"Hello World";

int myInt = 123456;
NSString* myString = [NSString stringWithFormat:@"%i", myInt];
  • 문자열 이어 붙여 출력하기
/// 문자열 이어 붙이기 - 1
NSString* resString = [NSString stringWithFormat:@"%@ %@", stringOne, stringTwo]; 

/// 문자열 이어 붙이기 - 2
NSLog(@"%@ %@", stringOne, stringTwo);

/// 문자열 이어 붙이기 - 3
NSString* thirdString = [stringOne stringByAppendingString:@" "];
thirdString = [thirdString stringByAppendingString:stringTwo];
NSLog(@"Result: %@", thirdString);

/// 출력결과 - 3
Result: Hello World

/// Mutable String
NSMutableString* myMutableString = [NSMutableString stringWithString: stringOne];

[myMutableString appendString: @" "];
[myMutableString appendString: stringTwo];

If - Else

  • 기본적인 If-Else 문 사용
BOOL networkDataIsFetched = true;

if (networkDataIsFetched) {
		NSLog(@"데이터를 성공적으로 가져왔습니다.");
} else {
		NSLog(@"가져오는 중입니다.");
}
  • If - else if - else 문 사용
if (a > b) {
		NSLog(@"A is bigger");
} else if (a < b) {
		NSLog(@"A is smaller");
} else {
		NSLog(@"They are equal");
}

Array & Set

Objective-C 에서는 NSArray 와 NSMutableArray 가 존재합니다.

NSArray 는 불변객체, 즉 한 번 생성되면 변경할 수 없는 문제가 있습니다. 요소를 추가하거나 삭제할 수 없습니다.

NSMutableArray 는 가변 객체, 즉 생성 후에도 요소를 추가, 삭제, 교체할 수 있습니다. 배열의 크기를 동적으로 변경 가능합니다.

  • NSArray 사용
// NSArray 선언
NSArray* daysArr;

// Array 초기화
daysArr = [[NSArray alloc] initWithObjects: @"월요일", @"화요일", @"수요일", @"목요일", @"금요일", @"토요일", @"일요일", nil];

// Array에서 2번째 인덱스의 값을 꺼내고 싶다면?
NSLog(@"2번째 인덱스에 위치한 값: %@", [dayArr objectAtIndex:2]);
  • NSMutableArray 사용
// NSMutableArray 선언
NSMutableArray* daysArr;
// Array 초기화
daysArr = [[NSArray alloc] initWithObjects: @"월요일", @"화요일", @"수요일", @"목요일", @"금요일", @"토요일", @"일요일", nil];

// Array에 데이터 추가
[daysArr addObject:@"Friday"];

// Array의 데이터 삭제
[daysArr removeObject: @"Friday"];

// Array에서 특정 인덱스로 값 삭제
[daysArr removeObjectAtIndex: 0];

Objective-C 에서는 NSSet 와 NSMutableSet 가 존재합니다.

NSSet 는 불변객체, 즉 한 번 생성되면 변경할 수 없는 문제가 있습니다. 요소를 추가하거나 삭제할 수 없습니다. 그리고 Sets 내에서는 요소가 중복될 수 없습니다. 동일한 객체는 두 개 있을 수 없습니다.

NSMutableSet 는 가변 객체, 즉 생성 후에도 요소를 추가, 삭제, 교체할 수 있습니다. NSSet 과 마찬가지로 중복을 허용하지 않습니다.

  • NSSet 사용
NSSet* mySet = [[NSSet alloc] initWithObjects: @"Sunday", @"Monday", nil];

for (NSString* any in mySet) {
		if ( [any isEqualToString: @"Friday"]) {
			NSLog(@"There is Friday");
		}
}
  • NSMutableSet 사용
NSMutableSet *mutableSet = [NSMutableSet setWithObjects:@"Apple", @"Banana", nil];

/// Set 에 아이템 추가
[mutableSet addObject:@"Orange"];

/// Set 에 아이템 삭제
[mutableSet removeObject:@"Banana"];

/// Set 내에 특정 아이템이 있는지 확인하기
BOOL containsBanana = [mutableSet containsObject:@"Banana"]; // NO

Dictionaries

키와 값의 쌍으로 데이터를 관리하는 클래스

NSDictionary와 NSMutableDictionary로 나뉘며, 불변성과 가변성의 차이가 있습니다.

NSDictionary 는 불변 객체, 즉 한 번 생성되면 변경할 수 없습니다. 그리고 키 - 값 쌍을 추가하거나 삭제할 수 없습니다.

NSMutableDictionary 는 가변 객체 생성한 이후에도 추가, 삭제, 수정할 수 있습니다.

NSDictionary 는 NSMutableDictionary 는 각 키는 고유해야하기 때문에, 키에 nil 을 사용할 수 없습니다.

  • NSDictionary 사용
/// NSDictionary 생성 - 1
NSDictionary* myFirstDict = [NSDictionary dictionaryWithObject:@"Apple" forKey:@"애플"];

NSLog(@"Value for name is: %@", [myFirstDict objectForKey:@"애플"]);

/// NSDictionary 생성 - 2
NSDictionary *multValuesDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"Apple", @"애플",
                                @"Previous Swift", @"Objective-C",
                                @"New Swift", @"SwiftUI",
                                nil];

NSLog(@"MultValueDict: %@", multValuesDict);
  • NSMutableDictionary 사용
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary];

/// Dict 추가 - 1
[mutableDictionary setObject:@"value1" forKey:@"key1"];

/// Dict 추가 - 2
[mutableDictionary setObject:@"value2" forKey:@"key2"];

/// Dict 중 특정 Key 삭제
[mutableDictionary removeObjectForKey:@"key1"];

/// Dict 전체 삭제
[mutableDictionary removeAllObjects];

For 문

  • For 문 사용
for (int i = 0; i < 10; i++) {
		NSLog(@"Hello");
}

Switch 문

  • Switch 문 사용
int number = 2;

switch (number) {
    case 1:
        NSLog(@"Number is 1");
        break;
    case 2:
        NSLog(@"Number is 2");
        break;
    case 3:
        NSLog(@"Number is 3");
        break;
    default:
        NSLog(@"Number is not 1, 2, or 3");
        break;
}

While 문

Objective-C 에서 두 가지의 while 문을 사용할 수 있습니다.

while 문과 do-while 문입니다.

while 문은 반복 실행 전에 조건을 평가하며, 조건이 거짓이 되면 반복을 중지합니다.

do-while 문은 while 문과 유사하지만, 조건을 검사하기 전에 코드를 한 번 실행합니다. 따라서 코드 블록이 최소 한 번은 실행되는 것이 보장됩니다.

  • while 문
int i = 1;
while (1) {
    NSLog(@"i = %d", i);
    i++;
    if (i > 5) {
        break;
    }
}
  • do - while 문
int i = 1;
do {
    NSLog(@"i = %d", i);
    i++;
} while (i <= 5);

함수 - Function

  • 함수 기본 형태
반환형 함수이름(매개변수 목록) {
    // 함수 본문
}
  • 함수 사용 - 1
// 함수 정의
int add(int a, int b) {
    return a + b;
}

// 함수 호출
int result = add(3, 5);
NSLog(@"Result: %d", result); // Output: Result: 8
  • 함수 사용 - 2
@interface MyClass : NSObject
- (void)sayHello;
- (int)addNumber:(int)a toNumber:(int)b;
@end

@implementation MyClass
- (void)sayHello {
    NSLog(@"Hello from MyClass!");
}

/// Int 타입을 반환하면서, Int 타입 매개변수 2개를 받아들이는 함수
- (int)addNumber:(int)a toNumber:(int)b {
    return a + b;
}
@end

int main() {
    MyClass *myObject = [[MyClass alloc] init];
    [myObject sayHello]; // Output: Hello from MyClass!
    int sum = [myObject addNumber:3 toNumber:7];
    NSLog(@"Sum: %d", sum); // Output: Sum: 10
    return 0;
}
  • 반환값이 없는 함수
void greet() {
    NSLog(@"Hello, World!");
}

// 함수 호출
greet(); // Output: Hello, World!
  • 매개변수가 있는 함수
void printMessage(NSString *message) {
    NSLog(@"%@", message);
}

// 함수 호출
printMessage(@"Hello, Objective-C!"); // Output: Hello, Objective-C!
  • 매개변수가 여러개인 함수
int multiply(int a, int b) {
    return a * b;
}

// 함수 호출
int product = multiply(4, 5);
NSLog(@"Product: %d", product); // Output: Product: 20

0개의 댓글