在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:Avocarrot/ios-cheatsheet开源软件地址:https://github.com/Avocarrot/ios-cheatsheet开源编程语言:开源软件介绍:iOS CheatsheetA quick reference cheat sheet for iOS developers so that you turn coffee into code much faster:) Note: The Avocarrot team will do its best to keep this cheatsheet updated but feel free to send your pull requests if you want to add a new entry or edit something. ##Contents ###Objective-C Basics ###Foundation Framework Classes ###C Related Code ##Objective-C Basics ###Classes ####Class header @interface Human : NSObject
// Define properties and methods
@end ####Class implementation #import "Human.h"
@interface Human ()
// Define private properties and methods
@end
@implementation Human {
// Define private instance variables
}
// Provide method implementation code
@end ####Creating an instance Human * anObject = [[Human alloc] init]; ###Methods ####Defining methods // Returns nothing and has no arguments
- (void)foo;
// Returns an NSString object and takes one argument of type NSObject
- (NSString *)fooWithArgument:(NSObject *)bar;
// Takes two arguments one of type NSObject and a second one of type NSString
- (void)fooWithArgument:(NSObject *)bar andArgument:(NSString *)baz;
// Defines a class method (note the + sign)
+ (void)aClassMethod; ####Implementing methods - (NSString *)fooWithArgument:(NSObject *)bar{
// Do something here
return retValue;
} ####Calling a method [anObject someMethod];
[anObject someMethodWithArg1:arg1 andArg2:arg2]; OperatorsArithmetic Operators
Comparison Operators
Logical Operators
Compound Assignment Operators
Bitwise Operators
Other operators
###Properties ####Define properties @property (attribute1, attribute2) NSString *aProperty;
####Access Properties [anObject aProperty];
// Alternative
anObject.aProperty ###Constants ####Preprocessing Macros This is not an actual constant because it defines a macro which replaces all occurrences of #define MAX_NUMBER_OF_ITEMS 10 ####Using const A better approach is to use NSString *const kMyName = @"Clark"; ####Static and extern If you know that the constant will only be available within it's implementation file, then you can use static NSString * const kMyName = @"Clark"; If you want to have a constant global then you should use extern. // .h file
extern NSString * const kMyName; // .m file
NSString * const kMyName = @"Clark"; ###Flow control statements ####If-else statement if (someCondition) {
// Execute if the condition is true
} else if (someOtherCondition) {
// Execute if the other condition is true
} else {
// Execute if the none of the above conditions are true
} ####Ternary operator someCondition ? @"True" : @"False"; ####For Loops for (int i = 0; i < totalCount; i++) {
// Do something here
} ####While Loop while (someCondition) {
// Do something here
} ####Do While Loop do {
// Do something here
} while (someCondition); ####Switch switch (aLabel)
{
case kLabelA:
// Execute this if matched
break;
case kLabelB:
// Execute this if matched
break;
default:
// Execute this if matched
break;
} ###Delegates Delegates are a design pattern. A delegate allows one object to send messages to another object when an event happens. Check out [Apple docs](https:// developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html): ####Become the delegate of a framework class Step 1 Declare that your class adopts the protocol in the class definition in the angled brackets after the class/superclass name. // MyTableViewController.h
@interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@end Step 2 Set your object as the delegate. // MyTableViewController.m
[tableView setDelegate:self];
@end Step 3 Implement the delegate methods. ####Implement your own delegate for a custom class Step 1 Declare the protocol methods // Superman.h
#import <Foundation/Foundation.h>
@protocol SupermanDelegate <NSObject>
- (void)dodgeBullet;
- (void)seeThroughThings;
- (void)fly;
@optional
- (void)eat;
@end
@interface Superman : NSObject
// Create a property for the delegate reference
@property (nonatomic, weak) id <SupermanDelegate> delegate;
// Define other methods and properties
@end
Step 2 Set the delegate object // Superman.m
[self setDelegate:anObject]; Step 3 Start sending delegate messages // Superman.m
[self.delegate fly]; For the delegate methods that are optional, it is wise to check if the delegate can respond to that method before firing. if ([self.delegate respondsToSelector:@selector(eat)]) {
[self.delegate eat];
} Blocks
For more information see [Programming with Objective-C - Working with Blocks](https:// developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html) To declare a block local variable:
To declare a block property:
To accept a block as a method parameter:
To pass a block as an argument in a method call:
To define a block type: typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...}; ##Class Specific ###NSString ####Quick examples NSString *firstName = @"Clark";
NSString *lastName = @"Kent";
NSString *fullName = [NSString stringWithFormat: @"My full name is %@ %@", firstName, lastName]; ####NSString format specifier
###NSArray ####Quick examples // Create an array
NSMutableArray *anArray = [@[@"Clark Kent", @"Lois Lane"] mutableCopy];
// Add new items
[anArray addObject:@"Lex Luthor"];
// Find array length
NSLog(@"Array has %d items", [anArray count]);
// Iterate over array items
for (NSString *person in anArray) {
NSLog(@"Person: %@", person);
}
// Access item with index
NSString *superman = anArray[0];
// Remove Object @"Clark Kent"
[anArray removeObject:@"Clark Kent"];
// Remove the first Object
[anArray removeObjectAtIndex:0]; ###NSDictionary ####Quick examples // Create a dictionary
NSMutableDictionary *person = [@{
@"firstname" : @"Clark",
@"lastname" : @"Kent",
@"age" : [NSNumber numberWithInt:35]
} mutableCopy];
// Access values
NSLog(@"Superman's first name is %@", person[@"firstname"]);
// or
NSLog(@"Superman's first name is %@", [person objectForKey:@"firstname"]);
// Find number of items in dictionary
[person count];
// Add an object to a dictionary
[person setObject:@"job" forKey:@"teacher"];
// Remove an object to a dictionary
[person removeObjectForKey:@"firstname"]; ##Objective-C Literals Available from LLVM Compiler version 4.0 made available with Xcode 4.4 ###Strings NSString *string = @"This is a string."; ###Numbers NSNumber *number = @126; // int : Equal to [NSNumber numberWithInt:126];
NSNumber *number = @126u; // unsigned int : Equal to [NSNumber numberWithUnsignedInt:126u];
NSNumber *number = @126l; // long : Equal to [NSNumber numberWithLong:126l];
NSNumber *number = @126.544f; // float : Equal to [NSNumber numberWithFloat:126.544f]
NSNumber *number = @126.544; // double : Equal to [NSNumber numberWithDouble:126.544]
NSNumber *number = @YES; // bool : Equal to [NSNumber numberWithBool:YES] ###Containers NSArray *array = @[object1,object2,object3]; // Creating NSArray
Object *object2 = array[1]; // Accessing NSArray
mutableArray[1] = newObject; // Adding to NSMutableArray
NSDictionary *dictionary = @{ @"key1" : object1, @"key2" : object2, @"key3" : object3 }; // Creating NSDictionary
Object *object2 = dictionary[@"key2"]; // Accessing NSDictionary
mutableDictionary[@"name"] = @"Henry"; // Adding to NSMutableDictionary ##C References ###Enumerated Types ####Apple's Examples Each enumerate is given a corresponding integer value, so typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom,
UIButtonTypeSystem,
UIButtonTypeDetailDisclosure,
UIButtonTypeInfoLight,
UIButtonTypeInfoDark,
UIButtonTypeContactAdd,
UIButtonTypeRoundedRect
}; is the same as typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom = 0,
UIButtonTypeSystem = 1,
UIButtonTypeDetailDisclosure = 2,
UIButtonTypeInfoLight = 3,
UIButtonTypeInfoDark = 4,
UIButtonTypeContactAdd = 5,
UIButtonTypeRoundedRect = 6
}; Explicitly defining the first enumerate's value is not required and it will default to 0. ####Using an enumerated type UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoLight]; Or create a variable to pass into the methods like so... UIButtonType myButtonType = UIButtonTypeCustom;
UIButton *myButton = [UIButton buttonWithType:myButtonType]; Because they are not objects, you must print enumerated types as integers UIButtonType myButtonType = UIButtonTypeRoundedRect;
// Bad, will give you a warning and might even crash
NSLog(@"%@", myButtonType);
// Good, will properly print the value as an integer
NSLog(@"%d", myButtonType); |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论