DevPrep

All topics › Objective-C

Why don't we use strong for an enum in Objective-C?

Junior PRO

Essence

strong, weak, copy are ownership attributes: they describe how a property retains an object (a reference-counted heap pointer). An enum in Objective-C is a plain C integer (NSInteger/NSUInteger via NS_ENUM/NS_OPTIONS): it is stored directly in the ivar, has no retain count and there is nothing to retain. The same applies to BOOL, CGFloat, NSTimeInterval, structs (CGRect), SEL, C pointers.

For such properties the ownership attribute is assign (also the default for non-objects; written explicitly for readability):

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, LoadState) {
    LoadStateIdle,
    LoadStateLoading,
    LoadStateFailed,
};

@interface Loader : NSObject
@property (nonatomic, assign) LoadState state;      // scalar
@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, strong) NSError *lastError;   // object
@end

If you write strong for an enum, the compiler reports "property with 'retain (or strong)' attribute must be of object type".

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store