ObjectiveC 是一种面向对象的编程语言,通常用于 macOS 和 iOS 应用程序的开发。下面是一些简单的 ObjectiveC 编程示例,涵盖了基本的语法和常见的编程任务。
```objectivec
import
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Hello, World!");
}
return 0;
}
```
```objectivec
import
// 声明一个类
@interface Person : NSObject
// 属性
@property NSString *name;
@property int age;
// 方法
(void)introduce;
@end
// 实现类
@implementation Person
(void)introduce {
NSLog(@"My name is %@ and I am %d years old.", self.name, self.age);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 创建对象
Person *person = [[Person alloc] init];
person.name = @"John";
person.age = 30;
// 调用方法
[person introduce];
}
return 0;
}
```
```objectivec
import
// 父类
@interface Animal : NSObject
(void)sound;
@end
@implementation Animal
(void)sound {
NSLog(@"Animal makes a sound");
}
@end
// 子类
@interface Dog : Animal
@end
@implementation Dog
(void)sound {
NSLog(@"Dog barks");
}
@end
@interface Cat : Animal
@end
@implementation Cat
(void)sound {
NSLog(@"Cat meows");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 多态
Animal *animal;
animal = [[Dog alloc] init];
[animal sound]; // 输出 "Dog barks"
animal = [[Cat alloc] init];
[animal sound]; // 输出 "Cat meows"
}
return 0;
}
```
```objectivec
import
// 定义协议
@protocol PrinterDelegate
(void)print;
@end
// 实现协议的类
@interface Printer : NSObject
@property (nonatomic, weak) id
(void)startPrinting;
@end
@implementation Printer
(void)startPrinting {
if ([self.delegate respondsToSelector:@selector(print)]) {
[self.delegate print];
}
}
@end
// 实现协议的另一个类
@interface Document : NSObject
@end
@implementation Document
(void)print {
NSLog(@"Printing document...");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Printer *printer = [[Printer alloc] init];
Document *document = [[Document alloc] init];
printer.delegate = document;
[printer startPrinting]; // 输出 "Printing document..."
}
return 0;
}
```
这些示例覆盖了 ObjectiveC 中的基本概念,包括类、对象、继承、多态、协议和委托。通过这些示例,你可以开始学习和理解 ObjectiveC 编程语言的基础知识。
文章已关闭评论!
2024-11-26 16:37:43
2024-11-26 16:36:30
2024-11-26 16:35:06
2024-11-26 16:33:34
2024-11-26 16:32:12
2024-11-26 16:30:54
2024-11-26 16:29:37
2024-11-26 16:28:10