구조체는 여러 데이터 항목을 하나의 집합으로 묶는 데이터 구조다. 구조체를 정의하고 구조체의 변수를 선언해서 사용할 수 있고 기본값을 갖고 있을 수 없다. 주로 헤더파일에 정의하고, 구조체를 사용하려면 구조체를 정의한 헤더 파일을 import하고 인스턴스를 생성하여 사용한다. Objective-C에서 구조체는 기본적으로 메서드를 갖지 않고 멤버 변수만을 포함하여 주로 간단한 데이터 구조를 정의한다.
struct Books {
NSString *title;
NSString *author;
NSString *subject;
int book_id;
};
struct Books book1;
book1.title = @"Objective-C Programming";
book1.author = @"Nuha Ali";
book1.subject = @"Objective-C Programming Tutorial";
book1.book_id = 6495407;
struct Product {
int id;
float price;
char name[50];
};
Product product1 = {101, 29.99, "Apple"};
// 함수 인자로 사용 가능
void printPerson(Person p) {
NSLog(@"Name: %s", p.name);
NSLog(@"Age: %d", p.age);
NSLog(@"Height: %.1f", p.height);
}
// 함수 호출
printPerson(person1);
새로운 데이터 타입에 대한 별칭(alias)을 정의한다. 이를 통해 코드의 가독성을 높이고, 특정 데이터 타입을 더 이해하기 쉽게 만든다.
// 기본 데이터 타입 alias
typedef unsigned long ulong;
ulong largeNumber = 123456789;
// 구조체 alias
struct Person {
char *name;
int age;
};
typedef struct Person Person;
Person p;
p.name = "John";
p.age = 30;
// 익명 구조체: 구조체 타입 정의 시 구조체 이름 생략, 대신 typedef를 사용하여 별칭을 부여 (구조체를 정의하면서 동시에 별칭 부여)
typedef struct {
char *name;
int age;
} Person;
Person p;
p.name = "John";
p.age = 30;
// 배열 타입 alias
typedef int IntArray[10];
IntArray arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// 블록 타입 alias
typedef void (^CompletionBlock)(NSString *);
CompletionBlock block = ^(NSString *result) {
NSLog(@"Completion: %@", result);
};