Objective-C Tips

Time:2021-6-12

Notes & suggested usage

  • Bool is actually an 8-bit character type. If an integer value greater than 1 byte is assigned to bool, only the status character will be used as the bool value.

  • In the header file, other header files should be introduced as little as possible, and the@classClassname, or use the class protocol.

  • Try to use literal quantity: nsstring, nsnumber, nsarray, nsdictionary. Literal quantity form creation: use @ to express, @ “nsstring obj”, @ 1, @ [@ “val1”, @ “val2”], @ {@ “key”:@10 }。

  • Use less # define and more type constants: static const nsstring * kword = @ “word”; Instead of using # define word @ “word”. If it is not used publicly, try to put it in the implementation file.

  • Using NS_ ENUM, NS_ Options to define enumeration types and indicate their underlying data types. Don’t implement the default branch in the switch statement that deals with enumeration types. After adding a new enumeration, the compiler will prompt that switch does not deal with the newly added enumeration types.

selector

@Selector is a keyword of OC, which can be transformed into sel type and expressed as dynamic pointer.

-(void) callMe {}
-(void) callMeWithParam: (id)obj {}

SEL aMethod = @selector(callMe)
SEL bMethod = @selector(callMeWithParam)
//You can also use nsselectorfromstring to achieve better dynamic effect
// SEL aMethod = NSSelectorFromString(@"callMe")
// SEL bMethod = NSSelectorFromString(@"callMeWithParam")

Singleton mode

//Singleton.h
@interface Singleton : NSObject
+ (Singleton*)sharedManager;
@property (nonatomic ,strong) NSString* singletonData;
@end

//Singleton.m
#import "Singleton.h"
@implementation Singleton
@synthesize singletonData = _singletonData; static Singleton *sharedManager = nil;
+ (Singleton*)sharedManager
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}
@end