| 关键词: nbsp NSString 运算符 常量 anArray Clark NSObject firstName person anObject |
iOS开发快速参考备忘单帮助开发者们更快地进行iOS编码。 注:Avocarrot团队将会尽其最大努力更新这个备忘单,如果你想添加或编辑一些条目,请发送你的请求。 目录ClassesMethodsOperatorsPropertiesConstantsNSStringNSArrayNSDictionaryEnumerated TypesFlow control statementsDelegatesBlocks 类类标头@interface Human : NSObject // Define properties and methds @end 类实现#import "Human.h" @interface Human () // Define private properties and methods @end @implementation Human { // Define private instance variables } // Provide method implementation code @end 创建一个实例Human * anObject = [[Human alloc] init]; 方法定义方法// 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; 实现方法- (NSString *)fooWithArgument:(NSObject *)bar{ //Do something here return retValue; } 调用方法[anObject someMethod]; [anObject someMethodWithArg1:arg1 andArg2:arg2]; 运算符算术运算符比较运算符逻辑运算符复合赋值运算符位运算符其他运算符属性定义属性@property (attribute1, attribute2) NSString *aProperty; 访问属性[anObject aProperty]; //Alternative anObject.aProperty 常量预处理宏这并不是一个真正的常量,因为它定义了一个宏在编译之前用真正的值代替所有出现的MAX_NUMBER_OF_ITEMS #define MAX_NUMBER_OF_ITEMS 10 使用const一个更好的方法是使用constNSString *const kMyName = @"Clark"; Static和extern如果你知道只能在实现文件中使用常量,那么你可以用static。使用static意味着这个常量只能在该文件中可用。static NSString * const kMyName = @"Clark"; 如果你想定义一个全局常量,那么你应该使用extern。//.h file extern NSString * const kMyName; //.m file NSString * const kMyName = @"Clark"; NSString示例:NSString *firstName = @"Clark"; NSString *lastName = @"Kent"; NSString *fullName = [NSString stringWithFormat: @"My full name is %@ %@", firstName, lastName]; NSString格式限定符NSArray示例://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示例://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 dicitonary |