Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Objective-C ARC Patterns

БесплатноБез исполняемых скриптовНе проверен

Use when automatic Reference Counting in Objective-C including strong/weak references, retain cycles, ownership qualifiers, bridging with Core Foundation, and…

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

Objective-C ARC Patterns

Introduction

Automatic Reference Counting (ARC) is Objective-C's memory management system that automatically inserts retain and release calls at compile time. ARC eliminates most manual memory management while providing deterministic memory behavior and preventing common memory bugs like use-after-free and double-free.

Unlike garbage collection, ARC provides immediate deallocation when reference counts reach zero, making it suitable for resource-constrained environments like iOS. Understanding ARC's ownership rules, qualifiers, and patterns is essential for writing memory-safe Objective-C code and avoiding retain cycles.

This skill covers strong and weak references, ownership qualifiers, retain cycles, Core Foundation bridging, and best practices for ARC-based memory management.

Strong and Weak References

Strong references maintain ownership of objects and prevent deallocation, while weak references observe objects without preventing deallocation.

// Strong references (default)
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSArray *friends;
@property (nonatomic, strong) UIImage *photo;
@end

@implementation Person
@end

// Weak references
@interface ViewController : UIViewController
@property (nonatomic, weak) id<ViewControllerDelegate> delegate;
@property (nonatomic, weak) IBOutlet UILabel *nameLabel;
@end

@implementation ViewController
@end

@protocol ViewControllerDelegate <NSObject>
- (void)viewControllerDidFinish:(ViewController *)controller;
@end

// Using strong and weak
void strongWeakExample(void) {
    Person *person = [[Person alloc] init];
    person.name = @"Alice"; // Strong reference to NSString

    __weak Person *weakPerson = person; // Weak reference
    NSLog(@"Weak person: %@", weakPerson.name);

    person = nil; // Person deallocated
    NSLog(@"After nil: %@", weakPerson); // weakPerson is now nil
}

// Unowned references (unsafe_unretained)
@interface NodeOld : NSObject
@property (nonatomic, unsafe_unretained) NodeOld *parent;
@property (nonatomic, strong) NSArray<NodeOld *> *children;
@end

@implementation NodeOld
@end

// Weak vs unowned
@interface CommentOld : NSObject
@property (nonatomic, strong) NSString *text;
@property (nonatomic, weak) PostOld *post; // Weak: can be nil
@end

@interface PostOld : NSObject
@property (nonatomic, strong) NSArray<CommentOld *> *comments;
@end

@implementation CommentOld
@end

@implementation PostOld
@end

// Strong captures in blocks
void blockCaptureExample(void) {
    Person *person = [[Person alloc] init];
    person.name = @"Bob";

    // Strong capture
    void (^strongBlock)(void) = ^{
        NSLog(@"%@", person.name); // Captures person strongly
    };

    // Weak capture to avoid retain cycle
    __weak Person *weakPerson = person;
    void (^weakBlock)(void) = ^{
        NSLog(@"%@", weakPerson.name); // Captures weakly
    };

    strongBlock();
    weakBlock();
}

Strong references increment retain count, while weak references are automatically set to nil when the object deallocates, preventing dangling pointers.

Retain Cycles and Breaking Them

Retain cycles occur when objects hold strong references to each other, preventing deallocation. Breaking cycles requires weak or unowned references.

// Retain cycle example
@interface Parent : NSObject
@property (nonatomic, strong) NSArray<Child *> *children;
@end

@interface Child : NSObject
@property (nonatomic, weak) Parent *parent; // Weak to break cycle
@property (nonatomic, strong) NSString *name;
@end

@implementation Parent
- (void)dealloc {
    NSLog(@"Parent deallocated");
}
@end

@implementation Child
- (void)dealloc {
    NSLog(@"Child deallocated");
}
@end

void noCycleExample(void) {
    Parent *parent = [[Parent alloc] init];
    Child *child = [[Child alloc] init];
    child.name = @"Alice";
    child.parent = parent; // Weak reference

    parent.children = @[child]; // Strong reference
    // When parent goes out of scope, both deallocate
}

// Delegate pattern without cycles
@protocol DataSourceDelegate <NSObject>
- (void)dataSourceDidUpdate:(id)source;
@end

@interface DataSource : NSObject
@property (nonatomic, weak) id<DataSourceDelegate> delegate;
- (void)fetchData;
@end

@implementation DataSource
- (void)fetchData {
    // Fetch data
    [self.delegate dataSourceDidUpdate:self];
}

- (void)dealloc {
    NSLog(@"DataSource deallocated");
}
@end

// Block retain cycles
@interface NetworkManager : NSObject
@property (nonatomic, strong) NSString *baseURL;
- (void)fetchDataWithCompletion:(void (^)(NSData *data))completion;
@end

@implementation NetworkManager
- (void)fetchDataWithCompletion:(void (^)(NSData *))completion {
    // Simulate async work
    dispatch_async(dispatch_get_global_queue(
        DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [@"response" dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_asy
Полный SKILL.md на GitHub

Установить Objective-C ARC Patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Objective-C ARC Patterns?

Use when automatic Reference Counting in Objective-C including strong/weak references, retain cycles, ownership qualifiers, bridging with Core Foundation, and patterns for memory-safe code without manual retain/release.

Как установить скилл Objective-C ARC Patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Objective-C ARC Patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Objective-C ARC Patterns с