As lead of an iOS app whose Objective-C core now serves new Swift screens, which Objective-C header and compiler rules would you enforce to keep that core healthy?
answer
- the header is the contract
- assume-nonnull regions, explicit nullable
- warnings promoted to errors
- ARC everywhere, prefixed categories
- rewrite where change is frequent
basics
~20 sTreat each public header as the contract: wrap it in NS_ASSUME_NONNULL_BEGIN and END, mark the real nullables, add element types and designated initializers, turn nullability and implicit-self warnings into errors, finish ARC conversion, and fence categories and swizzling.
solid answer
~40 sI start with the headers the Swift code calls, because they are what every caller trusts. Each gets an `NS_ASSUME_NONNULL_BEGIN`/`END` region with `nullable` written only where `nil` is a real answer, element types such as `NSArray<NSURL *> *`, and `NS_DESIGNATED_INITIALIZER` with `NS_UNAVAILABLE` on `init` where a plain init would be invalid. Clang then helps: `-Wnullability-completeness` flags a half-annotated header and `-Wnonnull` a literal `nil` passed to a nonnull parameter, while the off-by-default `-Wnullable-to-nonnull-conversion` and `-Wimplicit-retain-self` catch more. Annotations are promises, not runtime checks, so a wrong `nonnull` is worse than none. On the language side: remaining manual-counting files get converted, categories on framework classes are prefixed, and swizzling lives in one reviewed place. I rewrite in Swift where the code changes often and keep stable, well-tested Objective-C behind clean headers.
code
objective-c · 19 lines#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface PPUploader : NSObject
@property (nonatomic, copy, nullable) NSString *lastErrorMessage;
@property (nonatomic, copy) NSArray<NSURL *> *photoURLs;
- (instancetype)initWithEndpoint:(NSURL *)endpoint NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
- (nullable NSData *)previewDataForPhotoAtIndex:(NSUInteger)index
error:(NSError **)error;
- (void)uploadWithCompletion:(void (^)(NSError * _Nullable error))completion;
@end
NS_ASSUME_NONNULL_ENDgo deeper
Recall what NS_ASSUME_NONNULL_BEGIN and nullable mean in a header and why a header is a contract.
Explain which clang warnings nullability enables, how designated initializers and NS_UNAVAILABLE shape construction, and why element types matter.
Show how a wrong annotation crashes far from its cause, and how you would audit a header against its implementation before marking it.
Own the plan: which modules get annotated and promoted to errors first, what is rewritten versus kept behind clean headers, and how strictness is phased so releases keep shipping.
## Why the header is where health starts In a mixed app, the Objective-C core is consumed mostly through its headers. Every caller, whether a Swift screen or another Objective-C file, reads the `.h` to learn what may be `nil`, what a collection holds and how an object must be created. An unannotated header says nothing about any of this, and Swift turns that silence into implicitly unwrapped types, which the material on Swift bridging covers. So the cheapest, highest-value rule is to make every header an honest contract. ## Header rules - **Nullability regions.** Wrap each header in `NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END`; the macros expand to clang's `assume_nonnull` pragma, so pointers in the region are nonnull unless marked. Mark `nullable` only where `nil` is a real result. Block parameters use the underscore form, `NSError * _Nullable error`. An `NSError **` out-parameter is not made nonnull by the region. Nullability annotations arrived with Xcode 6.3. - **Foundation's newer form.** Foundation's headers in the current SDK use `NS_HEADER_AUDIT_BEGIN(nullability, sendability)`; its header comment says the `nullability` keyword subsumes `NS_ASSUME_NONNULL_BEGIN/_END`. Adopting it is a choice, not a requirement. - **Element types.** Write `NSArray<NSURL *> *photoURLs` and `NSDictionary<NSString *, PPPrintOrder *> *` rather than bare collections; lightweight generics date from Xcode 7. - **Initializers.** Mark the real initializer `NS_DESIGNATED_INITIALIZER` and mark `init` `NS_UNAVAILABLE` when an uploader without an endpoint is meaningless; clang then reports "'init' is unavailable". - **Properties.** Explicit attributes everywhere, `nonatomic`, `copy` for strings and blocks, and `weak` delegates. - **Prefixes.** Class names and category methods on framework classes carry the app's prefix. ## Compiler rules | Diagnostic | Catches | Default | |---|---|---| | `-Wnullability-completeness` | a header annotated in some places but not others | on | | `-Wnonnull` | a literal `nil` passed to a nonnull parameter | on | | `-Wnullable-to-nonnull-conversion` | a nullable value passed where nonnull is required | off | | `-Warc-retain-cycles` | a stored block that obviously captures `self` | on | | `-Wimplicit-retain-self` | a bare ivar that captures `self` in a block | off | | `-Wobjc-property-implementation` | a category property with no accessors | on | Promote the ones you rely on to errors so a regression stops the build instead of joining a long warning list. ## Runtime habits to fence 1. **Manual reference counting.** Count the files still marked `-fno-objc-arc` and convert them as they are touched; manual files carry bug classes, over-release and leaks, that ARC removes. 2. **Swizzling.** Allow it in one reviewed place, installed from `+load` under `dispatch_once` and calling the original implementation, with a written reason. Swizzles scattered across categories make behaviour depend on load order. 3. **Categories.** Never override an existing method from a category; which implementation wins is undefined. 4. **Key-value observing.** Every `addObserver:forKeyPath:options:context:` has a matching `removeObserver:forKeyPath:context:` before the observer goes away. ## What to rewrite and what to keep There is no single right answer; these are the questions I weigh for each class: 1. **How often does it change?** Code edited every sprint gains most from a rewrite; code untouched for years mostly needs a good header. 2. **Can its API be stated honestly?** An interface built on `id`, on `nil` meaning several things, or on swizzled behaviour is a rewrite candidate, because annotations would lie. 3. **How well is it tested?** Stable, well-tested Objective-C is an asset; rewriting it buys risk without user value. 4. **What sits under it?** Code that leans on Objective-C dynamism, such as key-value observing or forwarding, is costly to port and often best left behind a clean header. ## The trade-offs a lead owns - **Annotation versus truth.** A `nonnull` that is sometimes false is worse than no annotation: callers drop their checks, and a later `nil` crashes far from its cause. Annotate from what the implementation does, not from what it should do. - **Strictness versus velocity.** Turning warnings into errors across a large old core can stall a release; promote them per module as each one is cleaned. - **Consistency versus churn.** Mass-editing headers creates noisy diffs and merge pain; annotating as files are touched spreads the cost but leaves gaps longer. - **Ownership of the rules.** Rules nobody checks decay. Put the warning flags in the shared build configuration rather than in individual targets, and make header review part of every change that touches the core, so new Objective-C code arrives annotated instead of joining the backlog.
- What does NS_ASSUME_NONNULL_BEGIN do, and what does it leave unchecked?It expands to clang's `assume_nonnull` pragma, so simple pointers between it and `NS_ASSUME_NONNULL_END` are nonnull unless marked. Nothing checks at run time that a method really returns non-nil or that callers never pass `nil`; clang warns only for literal `nil`, or for nullable values once `-Wnullable-to-nonnull-conversion` is on.
- Why is a wrong nonnull annotation worse than leaving a pointer unannotated?Unannotated means unspecified, so careful callers keep their nil checks. A wrong `nonnull` tells every caller and the compiler that nil cannot happen, so checks get removed, and when the method does return nil the failure surfaces somewhere else, often as a crash in calling code far from the real cause.
- When would you leave an Objective-C class as it is rather than rewrite it?When it is stable, well tested, rarely edited and its API can be annotated honestly. A clean header gives new callers most of the benefit at a fraction of the risk, and the rewrite can wait until a real change forces someone into the code anyway.
- NS_ASSUME_NONNULL_BEGIN makes the runtime reject nil arguments.
- Nullability annotations only matter to Swift; Objective-C callers gain nothing.
- Marking a method nonnull is safe even if it sometimes returns nil.
- The whole Objective-C core should be rewritten before any header is annotated.
- Swizzling from any category's +load is a harmless convenience.
- Leftover manual-counting files are fine forever because ARC interoperates.