前言
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] = ` `;
} else {
sprintf(str, "%d", (int)error);
}
fprintf(stderr, "[Error] %s (%s)
", 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#>
}