Objective-C简单教程(入门)-从官方文档中挑选

来源:互联网 发布:日本福岛核事故 知乎 编辑:程序博客网 时间:2024/04/29 22:37
  • 定义类,类名必须是唯一的
@interface SimpleClass : NSObject@end
  • 属性定义
@interface Person : NSObject@property NSString *firstName;@property NSString *lastName;@end
@interface Person : NSObject@property (readonly) NSString *firstName;@property (readonly) NSString *lastName;@end
  • 声明函数
- (void)someMethod;
  • 带参数的函数
- (void)someMethodWithValue:(SomeType)value;- (void)someMethodWithFirstValue:(SomeType)value1 secondValue:(AnotherType)value2;
  • 一般官方文档中函数表示为
    someMethodWithFirstValue:secondValue:

  • 类的实现

//头文件XYZPerson.h中XYZPerson 定义@interface XYZPerson : NSObject- (void)sayHello;@endXYZPerson 类的实现@implementation XYZPerson- (void)sayHello {    NSLog(@"Hello, World!");}@end
  • 类方法
+ (id)string;+ (id)stringWithString:(NSString *)aString;+ (id)stringWithFormat:(NSString *)format, …;+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc  error:(NSError **)error;+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;
  • 对象方法的调用
[someObject doSomething];
  • 指针同c(可以引用传递)
//带返回值的函数- (int)magicNumber {    return 42;}
  • 在类内部调用成员函数(self)
[self saySomething:@"Hello, world!"];
  • 内存分配及初始化函数(构造函数)
+ (id)alloc;- (id)init;
  • 调用
NSObject *newObject = [[NSObject alloc] init];//init函数可以自定义,即自定义构造函数
  • 使用工厂方法来创建对象是非常方便的
+ (NSNumber *)numberWithBool:(BOOL)value;+ (NSNumber *)numberWithFloat:(float)value;
  • 调用
NSNumber *magicNumber = [NSNumber numberWithInt:42];
  • 当然也可以使用new来创建对象(和C++类似)
XYZObject *object = [XYZObject new];
  • 字符串可以直接赋值
NSString *someString = @"Hello, World!”;
  • Objective-C是动态语言如id类型是不确定的类型
  • Objective-C的空对象为nil,还有布尔类型的值为NO、YES

  • 协议(类似java的接口或C++的抽象基类)

@protocol XYZPieChartViewDataSource- (NSUInteger)numberOfSegments;- (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;- (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;@end
@interface XYZPieChartView : UIView@property (weak) id <XYZPieChartViewDataSource> dataSource;...@end
@interface MyClass : NSObject <MyProtocol>...@end
@interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>...@end
  • 块语句(类似lamda表达式)
^{     NSLog(@"This is a block");}void (^simpleBlock)(void);simpleBlock = ^{    NSLog(@"This is a block");};void (^simpleBlock)(void) = ^{    NSLog(@"This is a block");};
0 0
原创粉丝点击