Mark method to never return zero

I am developing an API using Objective-C, this API has a protocol with some fictitious method:

- (NSString *)gimmeString; // Want implementations to never return nil

I am a big fan of providing context, so I use everything for this purpose heavily, including attributes like __attribute__((nonnull))friends. What am I asking if there is a way to provide context and possibly add compile-time checking to implement the method, saying "this method never returns nil" when compiling with clang?

i.e. I would like to have something like:

@protocol MyProtocol
- (NSString *)gimmeString __attribute__((no_I_never_really_really_return_that_weird_nil));
@end

@implementation MyProtocolAdopter
- (NSString *)gimmeString
{
    return nil; // WARNING! You're returning nil, YOU PROMISED!
}
@end

instead of just:

@protocol MyProtocol
// This method should never return nil
- (NSString *)gimmeString;
@end 

@implementation MyProtocolAdopter
- (NSString *)gimmeString
{
    // muvahaha, I lied!
    return nil;
}
@end

I understand that it is not possible to fully determine what is at compile time, but discovering return nil;or functions that certainly evaluate the value nilare fine.

- __attribute__((objc_method_family(copy))) , , , API .

+4
1

- XCode 6.3 -

XCode 6.3 , , nullable nonnull .

- (nonnull NSString *)gimmeString;


- Pre XCode 6.3 -

, clang gcc docs, , , Objective-C.

:

, , , - . , - . , could return nil - - , ,

return %something_which_evaluates_to_nil_at_compile_time%;

, , , , , - -init - -, , , .

-dequeueReusableCellWithIdentifier:forIndexPath: UITableView, , :

- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier
                           forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);


:

, , Objective-C, . :

@protocol MyProtocol
/**
 *  Creates and returns a string.
 *
 *  @note Implementations should never return nil.
 *
 *  @return A string, guarantied not to be nil.
 */
- (NSString *)gimmeString;
@end

, , , :

// Marks method to never return nil
#define MD_RETURNS_NONNULL

@protocol MyProtocol
/**
 *  Creates and returns a string.
 *
 *  @note Implementations should never return nil.
 *
 *  @return A string, guarantied not to be nil.
 */
- (NSString *)gimmeString MD_RETURNS_NONNULL;
@end

, , , , , .

Swift

, - . Swift , :

protocol MyProtocol {
    func gimmeString -> String
}

.

, Objective-C, , , , . , , , Swift, - , , . - , Swift .

UPD: OCLint, , - ( Clang).

+2

All Articles