Objective-C是一种面向对象的编程语言,广泛应用于iOS开发中。本文将详细解析Objective-C的基础语法,并提供相应的编程实例。
- 声明和定义类
Objective-C使用@interface关键字声明类,使用@implementation关键字定义类的实现。下面是一个简单的类声明和定义的示例:
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
- (void)introduce;
@end
@implementation Person
- (void)introduce {
NSLog(@"My name is %@ and I'm %ld years old.", self.name, (long)self.age);
}
@end
在上面的例子中,我们声明了一个名为Person的类,继承自NSObject。类中定义了两个属性:name和age,并提供了一个introduce方法用于打印人物信息。
- 对象的创建和使用
Objective-C使用alloc和init方法来创建对象。下面是一个创建Person对象并调用其方法的示例:
Person *person = [[Person alloc] init];
person.name = @"John";
person.age = 25;
[person in