Xcode snippets/objective-c learning

Time:2022-7-1

preface

Xcode-SnippetsIt is a pile of open source code on GitHub. Author Mattt shared his Xcode snippets. Today, let’s learn about them.

fragment

singleton.m

+ (instancetype)shared<#name#> {
    static <#class#> *_shared<#name#> = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shared<#name#> = <#initializer#>;
    });

    return _shared<#name#>;
}

Singleton, standard code.

stack.m

NSLog(@"Call Stack: %@", [NSThread callStackSymbols]);

This is interesting. What is the call stack of the output thread? I don’t know if it is true. The output is as follows:

Call Stack: (
    0   Countdown                           0x00000001000a73e4 -[AppDelegate application:didFinishLaunchingWithOptions:] + 120
    1   UIKit                               0x0000000186aeb124 <redacted> + 404
    2   UIKit                               0x0000000186d027e8 <redacted> + 2376
    3   UIKit                               0x0000000186d0519c <redacted> + 1504
    4   UIKit                               0x0000000186d0370c <redacted> + 184
    5   FrontBoardServices                  0x000000018a83d3c8 <redacted> + 32
    6   CoreFoundation                      0x0000000181fb827c <redacted> + 20
    7   CoreFoundation                      0x0000000181fb7384 <redacted> + 312
    8   CoreFoundation                      0x0000000181fb59a8 <redacted> + 1756
    9   CoreFoundation                      0x0000000181ee12d4 CFRunLoopRunSpecific + 396
    10  UIKit                               0x0000000186ae43d0 <redacted> + 552
    11  UIKit                               0x0000000186adef40 UIApplicationMain + 1488
    12  Countdown                           0x000000010013177c main + 124
    13  libdyld.dylib                       0x0000000194326a08 <redacted> + 4
)

strongself.m && weakself.m

__strong __typeof(<#weakSelf#>)strongSelf = <#weakSelf#>;
__weak typeof(self)weakSelf = self;

There is nothing to say about this. It is used to prevent circular references in blocks.

tu.m

Drunk

UIControlEventTouchUpInside

tvdel.m && tvds.m

These two are drunk, but they are very practical

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    <#statements#>
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return <#number#>;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return <#number#>;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#reuseIdentifier#> forIndexPath:<#indexPath#>];

    [self configureCell:cell forRowAtIndexPath:indexPath];

    return cell;
}

- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath
{
    <#statements#>
}

xae.m xaf.m xan.m xann.m xat.m

Assert debug macros, corresponding to
e-Equel
f-False
n-Nil
nn-NotNil
t-True

async.m

Asynchronous wait nesting of GCD.

dispatch_async(dispatch_get_global_queue(<#dispatch_queue_priority_t priority#>, <#unsigned long flags#>), ^(void) {
    <#code#>

    dispatch_async(dispatch_get_main_queue(), ^(void) {
        <#code#>
    });
});

cdfetch.m

The fetch code of coredata is actually provided by the official.

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:<#entityName#>];
fetchRequest.predicate = [NSPredicate predicateWithFormat:<#predicateFormat#>];

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:<#key#> ascending:<#isAscending#> selector:<#selector#>];
fetchRequest.sortDescriptors = @[sortDescriptor];

NSError *error;
NSArray *results = [<#context#> executeFetchRequest:fetchRequest error:&error];

if (error) {
    NSLog(@"%@", error);
}

Official version

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" inManagedObjectContext:<#context#>];
[fetchRequest setEntity:entity];
// Specify criteria for filtering which objects to fetch
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"<#format string#>", <#arguments#>];
[fetchRequest setPredicate:predicate];
// Specify how the fetched objects should be sorted
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#key#>"
                                                              ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

NSError *error = nil;
NSArray *fetchedObjects = [<#context#> executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
   <#Error handling code#>
}

checkerror.m

Annotation is used to translate ossatus error into a language that human beings can understand.

static void CheckError(OSStatus error, const char *operation) {
    if (error == noErr) {
      return;
    }

    char str[20];
    *(UInt32 *) (str + 1) = CFSwapInt32HostToBig(error);
    if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4])) {
        str[0] = str[5] = '\'';
        str[6] = '
static void CheckError(OSStatus error, const char *operation) {
if (error == noErr) {
return;
}
char str[20];
*(UInt32 *) (str + 1) = CFSwapInt32HostToBig(error);
if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4])) {
str[0] = str[5] = '\'';
str[6] = '\0';
} else {
sprintf(str, "%d", (int)error);
}
fprintf(stderr, "[Error] %s (%s)\n", operation, str);
exit(1);
}
'; } else { sprintf(str, "%d", (int)error); } fprintf(stderr, "[Error] %s (%s)\n", operation, str); exit(1); }

continuation.m

Fast in M file add anonymous category

@interface <#Class Name#> ()
<#Continuation#>
@end

cvds.m

Urinary

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section
{
    return <#numberOfItemsInSection#>;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:<#reuseIdentifier#> forIndexPath:indexPath];

    [self configureCell:cell forItemAtIndexPath:indexPath];

    return cell;
}

- (void)configureCell:(UICollectionViewCell *)cell
   forItemAtIndexPath:(NSIndexPath *)indexPath
{
    <# statements #>
}

documents.m

Remove the documents folder path from the app, which is quite practical

NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];

frame.m

This comparison 6. Terminology sugar realization, 66666

<# view #>.frame = ({
    CGRect frame = <# view #>.frame;
    <# ... #>
    frame;
});

frc.m

NSFetchedResultsControllerIt’s a good thing.

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:<#(NSString *)#>];
fetchRequest.predicate = [NSPredicate predicateWithFormat:<#(NSString *), ...#>];
fetchRequest.sortDescriptors = @[<#(NSSortDescriptor *), ...#>];

NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:<#(NSFetchRequest *)#> managedObjectContext:<#(NSManagedObjectContext *)#> sectionNameKeyPath:<#(NSString *)#> cacheName:<#(NSString *)#>];
fetchedResultsController.delegate = <#(id <NSFetchedResultsControllerDelegate>)#>;

NSError *error = nil;
if (![fetchedResultsController performFetch:&error]) {
    NSLog(@"Error: %@", error);
}

frcd.m

NSFetchedResultsControllerA bunch of callbacks

imv.m

This

[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"<#image name#>"]]

init.m

As the name suggests, it’s just an obsessive-compulsive disorder

self = [super init];
if (!self) {
  return nil;
}

<#initializations#>

return self;

library.m

Library path

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];

lifecycle.m

Most practical, none

#pragma mark - UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

mailcomp.m

Call system mail UI

#import <MessageUI/MessageUI.h>

- (void)presentModalMailComposerViewController:(BOOL)animated {
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *composeViewController = [[MFMailComposeViewController alloc] init];
        composeViewController.mailComposeDelegate = self;

        [composeViewController setSubject:<#Subject#>];
        [composeViewController setMessageBody:<#Body#> isHTML:YES];
        [composeViewController setToRecipients:@[<#Recipients#>]];

        [self presentViewController:composeViewController animated:animated completion:nil];
    } else {
        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil) message:NSLocalizedString(@"<#Cannot Send Mail Message#>", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil] show];
    }
}

#pragma mark - MFMailComposeViewControllerDelegate

- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error
{
    if (error) {
        NSLog(@"%@", error);
    }

    [self dismissViewControllerAnimated:YES completion:nil];
}

mark.m

Short, naturally combined egg

#pragma mark - <#Section#>

What is the difference with direct input.

nscoding.m

Implementation methods of nscoding protocol

#pragma mark - NSCoding

- (instancetype)initWithCoder:(NSCoder *)decoder {
    self = [super init];
    if (!self) {
      return nil;
    }

    <# implementation #>

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
  <# implementation #>
}

nsl.m

Short, natural and ovum 2, localized string

NSLocalizedString(@"<#Message#>", <#Comment#>)

pdel.m && pds.m

Uipickerview callback

#pragma mark - UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
  <#code#>
}

- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component
{
  <#code#>
}

#pragma mark - UIPickerDataSource

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
  return <#number#>
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
  return <#number#>
}

Recommended Today

Leetcode PHP题解–D127 455. Assign Cookies

D127 455. Assign Cookies topic link 455. Assign Cookies topic analysis Given two arrays, the first array represents the capacity of each container, and the second array represents the number of each item. The items need to be stuffed into the container, but there are two conditions. Condition 1: Only one item can be stuffed […]