Title here
Summary here
Structs in the target language are collections of fields, often used to group related data to form records.
This Person struct type has name and age fields.
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic) int age;
@end
@implementation Person
@end
Person* newPerson(NSString *name) {
Person *p = [[Person alloc] init];
if (p) {
p.name = name;
p.age = 42;
}
return p;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
// This syntax creates a new object.
Person *bob = [[Person alloc] init];
bob.name = @"Bob";
bob.age = 20;
NSLog(@"%@", bob);
// You can name the fields when initializing an object.
Person *alice = [[Person alloc] init];
alice.name = @"Alice";
alice.age = 30;
NSLog(@"%@", alice);
// Omitted fields will be zero-valued.
Person *fred = [[Person alloc] init];
fred.name = @"Fred";
// 'age' field is omitted, so it is zero-valued.
NSLog(@"%@", fred);
// Using a pointer to the object.
Person *ann = [[Person alloc] init];
ann.name = @"Ann";
ann.age = 40;
NSLog(@"%@", ann);
// Encapsulate new struct creation in constructor functions
Person *jon = newPerson(@"Jon");
NSLog(@"%@", jon);
// Access struct fields with a dot.
Person *sean = [[Person alloc] init];
sean.name = @"Sean";
sean.age = 50;
NSLog(@"%@", sean.name);
// Dots with object pointers - automatically dereferenced.
Person *sp = sean;
NSLog(@"%d", sp.age);
// Structs are mutable.
sp.age = 51;
NSLog(@"%d", sp.age);
// Anonymous struct type example.
struct {
NSString *name;
BOOL isGood;
} dog;
dog.name = @"Rex";
dog.isGood = YES;
NSLog(@"%@", dog.name);
}
return 0;
}To run this Objective-C code, ensure you have Foundation.framework linked, typically done by using clang or gcc:
$ clang -fobjc-arc -framework Foundation main.m -o main
$ ./main# Output example on successful run
{"name":"Bob", "age":20}
{"name":"Alice", "age":30}
{"name":"Fred", "age":0}
{"name":"Ann", "age":40}
{"name":"Jon", "age":42}
Sean
50
51
RexHere, we used Objective-C properties and methods to replicate the functionalities from the source language. Now that we understand how to define and manage data structures in Objective-C, let’s dive deeper into the language features.