前言
Xcode-Snippets
是github上的一堆开源代码。作者mattt分享了他的Xcode-Snippets(xcode代码片段),今天我们来学习一下。
片段
singleton.m
+ (instancetype)shared<#name#> {
static <#class#> *_shared<#name#> = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_shared<#name#> = <#initializer#>;
});
return _shared<#name#>;
}
单例,标准代码。
stack.m
NSLog(@"Call Stack: %@", [NSThread callStackSymbols]);
这个有点意思,输出线程的调用栈?不知道是不是真么翻译。输出如下:
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;
这个没啥好说的,用于防治block中循环引用。
tu.m
醉了
UIControlEventTouchUpInside
tvdel.m && tvds.m
这两个也醉了,不过蛮实用
#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
断言调试宏,分别对应
e-Equel
f-False
n-Nil
nn-NotNil
t-True
async.m
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
CoreData的fetch代码,其实官方自带的。
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);
}
官方版本
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
注释说用于把OSStatus error翻译成人类能看懂的语言。
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);
}
continuation.m
快速在.m文件添加匿名Category
@interface <#Class Name#> ()
<#Continuation#>
@end
cvds.m
尿性
#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
取App下Documents文件夹路径,还算实用
NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
frame.m
这个比较6。用语法糖实现,66666
<# view #>.frame = ({
CGRect frame = <# view #>.frame;
<# ... #>
frame;
});
frc.m
NSFetchedResultsController
是个好东西。
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
NSFetchedResultsController
的一堆回调
imv.m
这..
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"<#image name#>"]]
init.m
顾名思义了,不过是强迫症写法
self = [super init];
if (!self) {
return nil;
}
<#initializations#>
return self;
library.m
Library路径
[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
lifecycle.m
最实用,没有之一
#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
调用系统邮件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
短,然并卵
#pragma mark - <#Section#>
跟直接输入有什么区别。
nscoding.m
NSCoding协议实现相关方法
#pragma mark - NSCoding
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (!self) {
return nil;
}
<# implementation #>
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
<# implementation #>
}
nsl.m
短,然并卵2,本地化字符串
NSLocalizedString(@"<#Message#>", <#Comment#>)
pdel.m && pds.m
UIPickerView的回调
#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#>
}